Golang / GoLang System Architecture and Testing Interview Questions
How do you write Go benchmarks and what does -benchmem tell you?
Go's testing package has built-in benchmark support. Benchmarks identify performance regressions and allocation hotspots before they reach production. The -benchmem flag reveals hidden allocations that cause GC pressure.
// Benchmark function: func BenchmarkXxx(b *testing.B) func BenchmarkJSONMarshal(b *testing.B) { user := User{ID: 1, Name: "Alice", Email: "alice@example.com", Age: 30} b.ResetTimer() // start timing AFTER setup (exclude allocation of user) for i := 0; i < b.N; i++ { // b.N is calibrated by the framework _, err := json.Marshal(user) if err != nil { b.Fatal(err) } } } // Memory allocation benchmark func BenchmarkStringConcat(b *testing.B) { words := []string{"hello", "world", "foo", "bar", "baz"} b.ReportAllocs() // same as -benchmem for this specific benchmark b.ResetTimer() b.Run("plus operator", func(b *testing.B) { for i := 0; i < b.N; i++ { s := "" for _, w := range words { s += w } // alloc per iteration _ = s } }) b.Run("strings.Builder", func(b *testing.B) { for i := 0; i < b.N; i++ { var sb strings.Builder sb.Grow(50) // pre-allocate Γ’ΒΒ zero allocations inside loop for _, w := range words { sb.WriteString(w) } _ = sb.String() } }) } // Run commands: // go test -bench=. -benchmem ./... // go test -bench=BenchmarkStringConcat -benchtime=5s -count=3 // Sample output: // BenchmarkStringConcat/plus_operator-8 2345678 512 ns/op 256 B/op 5 allocs/op // BenchmarkStringConcat/strings.Builder-8 9876543 123 ns/op 64 B/op 1 allocs/op // Columns: name, iterations, ns per op, bytes per op, allocs per op
What -benchmem reports: 'B/op' is average bytes allocated per operation (heap). 'allocs/op' is the number of separate heap allocations per operation. Each allocation has overhead (~100ns) and increases GC pressure. Zero allocations in a hot path is the ideal target.
Comparing benchmarks: use benchstat (golang.org/x/perf/cmd/benchstat) to compare before/after with statistical significance β it reports percent change and p-values.
More Related questions...