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