Go Test Benchmark
In this tutorial, you'll learn about Go Test: Benchmarking. We cover key concepts, practical examples, and best practices.
Benchmark testing -- Write accurate Go benchmarks using the correct b.N iteration pattern.
The Problem
Go benchmarks must use b.N for the loop count. The testing framework adjusts b.N for stable timing. Expensive setup should be outside the loop using b.ResetTimer().
Wrong
func BenchmarkBad(b *testing.B) {
for i := 0; i < 1000; i++ { // Wrong! Fixed iteration count
expensiveOp()
}
}
Output:
// Not a valid benchmark. Does not measure correctly.
Right
func BenchmarkGood(b *testing.B) {
data := setupData() // Expensive setup
b.ResetTimer() // Don't count setup
for i := 0; i < b.N; i++ {
expensiveOp(data)
}
}
Output:
$ go test -bench=. -benchmem
BenchmarkGood-8 1000000 1234 ns/op 256 B/op 3 allocs/op
Prevention
- Always use b.N for loop iteration count
- Use b.ResetTimer() after expensive setup
- Use b.ReportAllocs() or -benchmem for alloc stats
- Use b.RunParallel() for concurrent benchmarks
- Multiple sub-benchmarks with b.Run()
Common Mistakes with test benchmark
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro