Golang / GoLang Production Patterns and Web Standards Interview Questions
How do you write and interpret Go benchmarks?
Go's testing package has built-in benchmark support. Benchmarks are functions with signature func BenchmarkXxx(b *testing.B) and run with go test -bench=.. The framework automatically calibrates the number of iterations.
// Benchmark function func BenchmarkJSONMarshal(b *testing.B) { user := User{ID: 1, Name: "Alice", Email: "alice@example.com"} b.ResetTimer() // exclude setup time from measurement for i := 0; i < b.N; i++ { // b.N is auto-calibrated _, err := json.Marshal(user) if err != nil { b.Fatal(err) } } } // Memory allocations benchmark func BenchmarkStringBuilder(b *testing.B) { words := []string{"hello", "world", "foo", "bar"} b.ReportAllocs() // show allocations in output b.ResetTimer() for i := 0; i < b.N; i++ { var sb strings.Builder for _, w := range words { sb.WriteString(w) sb.WriteByte(' ') } _ = sb.String() } } // Run benchmarks: // go test -bench=. -benchmem ./... // -benchmem: show memory allocations // -benchtime=5s: run for 5 seconds instead of default 1s // -count=5: run 5 times for stable results // Output: // BenchmarkJSONMarshal-8 1234567 987 ns/op 256 B/op 3 allocs/op // Columns: name, iterations, ns per op, bytes per op, allocs per op // Compare benchmarks with benchstat: // go test -bench=. -count=5 > before.txt // # make changes // go test -bench=. -count=5 > after.txt // benchstat before.txt after.txt # shows % improvement and p-value
More Related questions...