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 opWhat -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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
