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.
More Related questions...