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
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...
