Benchmarks With ReportAllocs
Measure throughput and allocations with testing.B, ReportAllocs, and sub-benchmarks so optimization claims rest on numbers you can reproduce.
Code
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)
}
})
}How it works
The functional core is concat, builder and BenchmarkBuild — everything else is wiring.
Repetition is confined to for _, part := range parts — the rest of the file is straight-line.
What to watch for
- Zero-fetch snippet: every identifier resolves inside the language distribution.
Putting it to use
What you call into: func BenchmarkBuild(b *testing.B)
BenchmarkBuild is what another module would consume; nothing else here is load-bearing for callers.
Core lines under the microscope
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
}
Interactive Tools for This Topic
A/B Test Sample Size CalculatorCalculate required per-variant sample size and experiment duration for two-proportion A/B tests from baseline conversion, MDE, alpha, and statistical power.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- Does it depend on any third-party library?
- No third-party library is referenced; the standard library covers it. The file defines `concat`, `builder`, `BenchmarkBuild` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.