Benchmarks
Write benchmarks to compare alternatives under realistic conditions, not to manufacture pretty numbers.
Canonical guidance
- benchmark representative operations
- compare real alternatives, not empty shells
- keep setup and measured work separated carefully
- use profiling when the benchmark shows meaningful cost
Use when
- performance comparisons
- regression tracking
- validating optimization claims
Avoid
- unrealistic microbenchmarks divorced from production behavior
- reading benchmark output without understanding allocations and setup cost
- changing code for benchmark wins that harm clarity without real impact
Preferred pattern
func BenchmarkParse(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = Parse(input)
}
}
Anti-pattern
- benchmark code that accidentally measures initialization more than the target operation
Explanation: This anti-pattern is common because benchmark harness code is easy to mix with setup, but that inflates numbers and makes comparisons meaningless.
Why
- benchmark numbers are only useful when the workload shape is credible
Related pages
Sources
- testing package - Go Team
- Profiling Go Programs - Russ Cox