Benchmark testing measures performance by repeatedly executing a function under consistent conditions. It reveals average processing time and helps compare alternative implementations before performance problems become production concerns. section 8.7.1
A practical benchmark follows a small, repeatable workflow:
- Start with a realistic implementation and establish a baseline. section 8.7.1
- Write a benchmark function that accepts *testing.B rather than *testing.T. section 8.7.1
- Run the operation through b.N iterations, checking that each result remains valid. section 8.7.1
- Run go test -bench=. and compare iterations, nanoseconds per operation, and the environment reported with the result. section 8.7.1
- Keep comparison parameters equivalent while changing the implementation under test. section 8.7.1
Comparing string-generation implementations
A RandomString function first builds a byte slice, then a second implementation uses strings.Builder. Separate benchmarks call each function with varying lengths and verify the returned length. Running go test -bench=. produces averaged nanoseconds-per-operation results, making the two approaches directly comparable; the measured result depends partly on the processor and operating system. section 8.7.1
Listing 8.34 xstrings_test.go: Simple string-generation method
import (
"strings"
"testing"
xstring "github.com/go-in-action/chpt_8/benchmark/xstring"
)
func BenchmarkRandomString(b *testing.B) { #1
for i := range b.N { #2
res := xstring.RandomString(i) #3
if len(res) != i {
b.Error("result has the wrong length")
}
}
}
Inspect the benchmark structure: testing.B supplies the iteration count, the loop invokes the function repeatedly, and the assertion catches invalid results. section 8.7.1






















