Skip to content

Commit 43e38d5

Browse files
committed
bytes: don't compact Buffer so aggressively
benchmark old ns/op new ns/op delta BenchmarkBufferNotEmptyWriteRead 848416 819983 -3.35% Update #5154 R=golang-dev, gri, robryk CC=golang-dev https://golang.org/cl/8173043
1 parent 994f596 commit 43e38d5

File tree

2 files changed

+9
-5
lines changed

2 files changed

+9
-5
lines changed

src/pkg/bytes/buffer.go

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,9 +87,11 @@ func (b *Buffer) grow(n int) int {
8787
var buf []byte
8888
if b.buf == nil && n <= len(b.bootstrap) {
8989
buf = b.bootstrap[0:]
90-
} else if m+n <= cap(b.buf) {
91-
// We can slide things down instead of
92-
// allocating a new slice.
90+
} else if m+n <= cap(b.buf)/2 {
91+
// We can slide things down instead of allocating a new
92+
// slice. We only need m+n <= cap(b.buf) to slide, but
93+
// we instead let capacity get twice as large so we
94+
// don't spend all our time copying.
9395
copy(b.buf[:], b.buf[b.off:])
9496
buf = b.buf[:m]
9597
} else {

src/pkg/bytes/buffer_test.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -490,8 +490,10 @@ func TestBufferGrowth(t *testing.T) {
490490
}
491491
}
492492
cap1 := b.Cap()
493-
if cap1 > cap0 {
494-
t.Errorf("buffer cap = %d; too big", cap1)
493+
// (*Buffer).grow allows for 2x capacity slop before sliding,
494+
// so set our error threshold at 3x.
495+
if cap1 > cap0*3 {
496+
t.Errorf("buffer cap = %d; too big (grew from %d)", cap1, cap0)
495497
}
496498
}
497499

0 commit comments

Comments
 (0)