实现说明
全部逻辑都在函数 concat、builder、BenchmarkBuild中。
这个示例中仅有的重复出现在 for _, part := range parts 里。
使用要点
- 不依赖任何第三方包,全部使用语言内建 API。
- 值得导入的表面是
BenchmarkBuild;周围的辅助代码对片段是私有的。
常见问题
它依赖第三方库吗?
没有引用任何第三方库,标准库就够了。 文件在加载时定义 concat、builder、BenchmarkBuild。
签名一览:func BenchmarkBuild(b *testing.B)
核心语句
func builder(parts []string) string {
var b strings.Builder
for _, part := range parts {
b.WriteString(part)
b.WriteByte(',')
}
return b.String()
}
func concat(parts []string) string {
out := ""
for _, part := range parts {
out += part + ","
}
return out
}
代码示例
package bench
import (
"strings"
"testing"
)
func concat(parts []string) string {
out := ""
for _, part := range parts {
out += part + ","
}
return out
}
func builder(parts []string) string {
var b strings.Builder
for _, part := range parts {
b.WriteString(part)
b.WriteByte(',')
}
return b.String()
}
// go test -bench=BenchmarkBuild -benchmem
// Sub-benchmarks compare both builders; ReportAllocs shows bytes and allocations per op.
func BenchmarkBuild(b *testing.B) {
parts := []string{"alpha", "beta", "gamma", "delta", "epsilon"}
b.Run("concat", func(b *testing.B) {
b.ReportAllocs() // 记录每次操作的分配次数与字节数
for i := 0; i < b.N; i++ {
_ = concat(parts)
}
})
b.Run("builder", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = builder(parts)
}
})
}