测试字符相加,两种方法,buffer相加明显快很多
benchmark_test.go
package benchmark
import (
"bytes"
"testing"
)
func BenchmarkConcatStringByAdd(b *testing.B) {
elem := []string{"1", "2", "3", "4", "5"}
b.ResetTimer()
for i := 0; i < b.N; i++ {
ret := ""
for _, v := range elem {
ret += v
}
}
b.StopTimer()
}
func BenchmarkConcatStringByByteBuffer(b *testing.B) {
elems := []string{"1", "2", "3", "4", "5"}
b.ResetTimer()
for i := 0; i < b.N; i++ {
var buf bytes.Buffer
for _, elem := range elems {
buf.WriteString(elem)
}
}
b.StopTimer()
}
执行:进入benchmark_test.go所在同级目录
go test -bench=.
想要查看什么原因导致满: go test -bench=. -benchmem
benchmark>go test -bench=.
goos: windows
goarch: amd64
pkg: src/benchmark
cpu: Intel(R) Core(TM) i5-7300U CPU @ 2.60GHz
BenchmarkConcatStringByAdd-4 7396891 152.5 ns/op
BenchmarkConcatStringByByteBuffer-4 15523389 74.26 ns/op
PASS
ok src/benchmark 2.806s
benchmark>go test -bench=. -benchmem
goos: windows
goarch: amd64
pkg: src/benchmark
cpu: Intel(R) Core(TM) i5-7300U CPU @ 2.60GHz
BenchmarkConcatStringByAdd-4 7556474 152.4 ns/op 16 B/op 4 allocs/op
BenchmarkConcatStringByByteBuffer-4 16703692 71.01 ns/op 64 B/op 1 allocs/op
PASS
ok src/benchmark 2.620s