Skip to content

Commit b1accce

Browse files
committed
strings: add Builder benchmarks comparing bytes.Buffer and strings.Builder
Despite the existing test that locks in the allocation behavior, people really want a benchmark. So: BenchmarkBuildString_Builder/1Write_NoGrow-4 20000000 60.4 ns/op 48 B/op 1 allocs/op BenchmarkBuildString_Builder/3Write_NoGrow-4 10000000 230 ns/op 336 B/op 3 allocs/op BenchmarkBuildString_Builder/3Write_Grow-4 20000000 102 ns/op 112 B/op 1 allocs/op BenchmarkBuildString_ByteBuffer/1Write_NoGrow-4 10000000 125 ns/op 160 B/op 2 allocs/op BenchmarkBuildString_ByteBuffer/3Write_NoGrow-4 5000000 339 ns/op 400 B/op 3 allocs/op BenchmarkBuildString_ByteBuffer/3Write_Grow-4 5000000 316 ns/op 336 B/op 3 allocs/op I don't think these allocate-as-fast-as-you-can benchmarks are very interesting because they're effectively just GC benchmarks, but sure. If one wants to see that there's 1 fewer allocation, there it is. The ns/op and B/op numbers will change as the built string size changes. Updates #18990 Change-Id: Ifccf535bd396217434a0e6989e195105f90132ae Reviewed-on: https://go-review.googlesource.com/96980 Run-TryBot: Brad Fitzpatrick <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Alan Donovan <[email protected]>
1 parent 495eb3f commit b1accce

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/strings/builder_test.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,3 +302,52 @@ func TestBuilderCopyPanic(t *testing.T) {
302302
}
303303
}
304304
}
305+
306+
var someBytes = []byte("some bytes sdljlk jsklj3lkjlk djlkjw")
307+
308+
var sinkS string
309+
310+
func benchmarkBuilder(b *testing.B, f func(b *testing.B, numWrite int, grow bool)) {
311+
b.Run("1Write_NoGrow", func(b *testing.B) {
312+
b.ReportAllocs()
313+
f(b, 1, false)
314+
})
315+
b.Run("3Write_NoGrow", func(b *testing.B) {
316+
b.ReportAllocs()
317+
f(b, 3, false)
318+
})
319+
b.Run("3Write_Grow", func(b *testing.B) {
320+
b.ReportAllocs()
321+
f(b, 3, true)
322+
})
323+
}
324+
325+
func BenchmarkBuildString_Builder(b *testing.B) {
326+
benchmarkBuilder(b, func(b *testing.B, numWrite int, grow bool) {
327+
for i := 0; i < b.N; i++ {
328+
var buf Builder
329+
if grow {
330+
buf.Grow(len(someBytes) * numWrite)
331+
}
332+
for i := 0; i < numWrite; i++ {
333+
buf.Write(someBytes)
334+
}
335+
sinkS = buf.String()
336+
}
337+
})
338+
}
339+
340+
func BenchmarkBuildString_ByteBuffer(b *testing.B) {
341+
benchmarkBuilder(b, func(b *testing.B, numWrite int, grow bool) {
342+
for i := 0; i < b.N; i++ {
343+
var buf bytes.Buffer
344+
if grow {
345+
buf.Grow(len(someBytes) * numWrite)
346+
}
347+
for i := 0; i < numWrite; i++ {
348+
buf.Write(someBytes)
349+
}
350+
sinkS = buf.String()
351+
}
352+
})
353+
}

0 commit comments

Comments
 (0)