diff options
author | rw <me@rwinslow.com> | 2015-04-02 19:33:00 -0700 |
---|---|---|
committer | rw <me@rwinslow.com> | 2015-04-02 19:33:00 -0700 |
commit | d756efbf764af942ef0563b2a1141349fbc4e72b (patch) | |
tree | 38658f8c5db10dee34247581a3084d1ad8717a0b /go/builder.go | |
parent | ace7fa8094de5ba92a74dce63903f8386d30e8b8 (diff) | |
download | flatbuffers-d756efbf764af942ef0563b2a1141349fbc4e72b.tar.gz flatbuffers-d756efbf764af942ef0563b2a1141349fbc4e72b.tar.bz2 flatbuffers-d756efbf764af942ef0563b2a1141349fbc4e72b.zip |
Reduce allocations when reusing a Builder.
Add the function `Reset` to the Builder, which facilitates reuse of the
underlying byte slice.
Diffstat (limited to 'go/builder.go')
-rw-r--r-- | go/builder.go | 31 |
1 files changed, 25 insertions, 6 deletions
diff --git a/go/builder.go b/go/builder.go index cdae6959..d8be2048 100644 --- a/go/builder.go +++ b/go/builder.go @@ -31,6 +31,15 @@ func NewBuilder(initialSize int) *Builder { return b } +// Reset truncates the underlying Builder buffer, facilitating alloc-free +// reuse of a Builder. +func (b *Builder) Reset() { + b.Bytes = b.Bytes[:0] + b.head = UOffsetT(0) + b.minalign = 1 + b.vtables = b.vtables[:0] +} + // StartObject initializes bookkeeping for writing a new object. func (b *Builder) StartObject(numfields int) { b.notNested() @@ -155,13 +164,23 @@ func (b *Builder) growByteBuffer() { if (int64(len(b.Bytes)) & int64(0xC0000000)) != 0 { panic("cannot grow buffer beyond 2 gigabytes") } - newSize := len(b.Bytes) * 2 - if newSize == 0 { - newSize = 1 + newLen := len(b.Bytes) * 2 + if newLen == 0 { + newLen = 1 + } + + if cap(b.Bytes) >= newLen { + b.Bytes = b.Bytes[:newLen] + } else { + extension := make([]byte, newLen-len(b.Bytes)) + b.Bytes = append(b.Bytes, extension...) + } + + middle := newLen / 2 + copy(b.Bytes[middle:], b.Bytes[:middle]) + for i := 0 ; i < middle; i++ { + b.Bytes[i] = 0 } - bytes2 := make([]byte, newSize) - copy(bytes2[newSize-len(b.Bytes):], b.Bytes) - b.Bytes = bytes2 } // Head gives the start of useful data in the underlying byte buffer. |