Golang / Golang Internals and Memory Management Interview Questions
How do you write and run benchmarks in Go?
Go's testing package includes a built-in benchmark framework. Benchmarks are functions with the signature func BenchmarkXxx(b *testing.B) and run with go test -bench=.. The framework handles warm-up and calibrates the number of iterations automatically.
// benchmark_test.go func BenchmarkStringConcat(b *testing.B) { // b.N is set by the framework â run the measured code exactly b.N times for i := 0; i < b.N; i++ { s := "" for j := 0; j < 100; j++ { s += "x" // inefficient â baseline } _ = s } } func BenchmarkStringBuilder(b *testing.B) { for i := 0; i < b.N; i++ { var sb strings.Builder for j := 0; j < 100; j++ { sb.WriteString("x") } _ = sb.String() } } // Run benchmarks: // go test -bench=. -benchmem ./... // BenchmarkStringConcat-8 123456 9876 ns/op 5264 B/op 99 allocs/op // BenchmarkStringBuilder-8 456789 2345 ns/op 128 B/op 2 allocs/op // -benchmem: shows memory allocations per op // -benchtime=5s: run each benchmark for 5 seconds // -count=5: run each benchmark 5 times for statistical stability // Reset timer to exclude setup time func BenchmarkWithSetup(b *testing.B) { data := make([]byte, 1<<20) // setup â excluded from timing b.ResetTimer() // start timing from here for i := 0; i < b.N; i++ { process(data) } } // Run with pprof to get a flame graph: // go test -bench=BenchmarkStringConcat -cpuprofile=cpu.out // go tool pprof cpu.out
The benchstat tool (part of golang.org/x/perf) compares two sets of benchmark results statistically, accounting for variance — essential for determining whether an optimisation is genuinely significant or within noise.
More Related questions...