Golang / Golang Internals and Memory Management Interview Questions
What is the Go optimisation workflow? How do you go from a performance problem to a fix?
Premature optimisation is wasteful; uninformed optimisation is harmful. The Go ecosystem provides a disciplined, measurement-driven workflow: profile first, identify the actual bottleneck, optimise, verify the improvement, and repeat.
// Step 1: establish baseline with benchmarks
// go test -bench=BenchmarkFoo -count=5 -benchmem > before.txt
// Step 2: collect a CPU profile
// go test -bench=BenchmarkFoo -cpuprofile=cpu.out
// go tool pprof cpu.out
// (pprof) top10 — hottest functions
// (pprof) web — flame graph (requires graphviz)
// (pprof) list hotFunc — annotated source
// Step 3: collect a memory profile
// go test -bench=BenchmarkFoo -memprofile=mem.out
// go tool pprof mem.out
// (pprof) top10 -cum — allocation hotspots
// Step 4: check escape analysis — are expected stack allocs escaping?
// go build -gcflags="-m -m" ./...
// Step 5: common optimisations to check:
// - Replace []byte string(b) conversions in hot paths
// - Pre-allocate slices with known capacity: make([]T, 0, n)
// - Use sync.Pool for frequently allocated/freed objects
// - Replace interface{} parameters with generics (Go 1.18+)
// - Replace reflect with code generation (go generate)
// - Use buffered I/O (bufio.Writer) instead of unbuffered
// Step 6: verify improvement
// go test -bench=BenchmarkFoo -count=5 -benchmem > after.txt
// benchstat before.txt after.txt
// Outputs: delta, p-value, whether improvement is statistically significant
// Step 7: run with -race to ensure no correctness regression
// go test -race ./...The golden rule: measure first. Intuition about where time is spent is usually wrong. The pprof CPU profile shows the actual hot path. A 10% improvement in a function that takes 1% of total time is invisible; a 10% improvement in a function that takes 80% is significant. Use benchstat to confirm improvements are statistically significant and not just 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...
