Skip to content

Instantly share code, notes, and snippets.

@bwangelme bwangelme/builder_test.go Secret
Created Apr 28, 2019

Embed
What would you like to do?
var someBytes = []byte("some bytes sdljlk jsklj3lkjlk djlkjw")
var sinkS string
func benchmarkBuilder(b *testing.B, f func(b *testing.B, numWrite int, grow bool)) {
b.Run("1Write_NoGrow", func(b *testing.B) {
b.ReportAllocs()
f(b, 1, false)
})
b.Run("3Write_NoGrow", func(b *testing.B) {
b.ReportAllocs()
f(b, 3, false)
})
b.Run("3Write_Grow", func(b *testing.B) {
b.ReportAllocs()
f(b, 3, true)
})
}
func BenchmarkBuildString_Builder(b *testing.B) {
benchmarkBuilder(b, func(b *testing.B, numWrite int, grow bool) {
for i := 0; i < b.N; i++ {
var buf Builder
if grow {
buf.Grow(len(someBytes) * numWrite)
}
for i := 0; i < numWrite; i++ {
buf.Write(someBytes)
}
sinkS = buf.String()
}
})
}
func BenchmarkBuildString_ByteBuffer(b *testing.B) {
benchmarkBuilder(b, func(b *testing.B, numWrite int, grow bool) {
for i := 0; i < b.N; i++ {
var buf bytes.Buffer
if grow {
buf.Grow(len(someBytes) * numWrite)
}
for i := 0; i < numWrite; i++ {
buf.Write(someBytes)
}
sinkS = buf.String()
}
})
}
// 以下是性能测试的运行结果,可以看到 strings.Builder 的运行时间和所用空间都比 bytes.Buffer 要小
// 而且可以看到,用户主动执行 Grow 后,程序分配内存的次数少了,时间也大大加快
//>>> go test -v -bench=BenchmarkBuild -run='^$' builder_test.go 22:11:37 (04-26)
//goos: darwin
//goarch: amd64
//BenchmarkBuildString_Builder/1Write_NoGrow-4 20000000 78.2 ns/op 48 B/op 1 allocs/op
//BenchmarkBuildString_Builder/3Write_NoGrow-4 5000000 305 ns/op 336 B/op 3 allocs/op
//BenchmarkBuildString_Builder/3Write_Grow-4 10000000 112 ns/op 112 B/op 1 allocs/op
//BenchmarkBuildString_ByteBuffer/1Write_NoGrow-4 10000000 139 ns/op 112 B/op 2 allocs/op
//BenchmarkBuildString_ByteBuffer/3Write_NoGrow-4 3000000 438 ns/op 352 B/op 3 allocs/op
//BenchmarkBuildString_ByteBuffer/3Write_Grow-4 5000000 324 ns/op 224 B/op 2 allocs/op
//PASS
//ok command-line-arguments 9.987s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.