Explain inuse_space vs alloc_space in a heap profile. Which do you use to find a memory leak vs GC pressure?
Question 371MediumGo 1.22 to 1.25
The heap profile records allocation sites, sampled on average once per runtime.MemProfileRate bytes (default 512 KiB). It offers four sample types:
- inuse_space / inuse_objects: memory allocated and not yet freed as of the most recent GC. Use this for leaks and high RSS.
- alloc_space / alloc_objects: everything allocated since program start, freed or not. Use this for GC pressure / CPU spent in mallocgc.
go tool pprof -sample_index=inuse_space http://host:6060/debug/pprof/heap
go tool pprof -sample_index=alloc_objects http://host:6060/debug/pprof/allocs
# leak hunting: diff two snapshots taken minutes apart
go tool pprof -base heap1.pb.gz heap2.pb.gz
Gotchas: (1) the data reflects the last completed GC, so it lags reality; (2) it shows where memory was allocated, not who is retaining it — a leak often shows up as a growing slice/map in a long-lived struct, or as goroutines holding references; (3) the heap profile does not include goroutine stacks, OS memory not yet returned, or cgo allocations, so RSS can exceed it. Check runtime/metrics or GODEBUG=gctrace=1 for the full picture.
More on Performance, Profiling & Testing
- Q369How do you expose pprof in a production service, and what are the security and design gotchas?
- Q370How does the Go CPU profiler work, and what is the difference between "flat" and "cum" in pprof output?
- Q372How would you detect and diagnose a goroutine leak?
- Q373What do the block and mutex profiles measure, how do you enable them, and how do they differ?
- Q374When would you use go tool trace instead of pprof? What can it show that profiles cannot?
- Q375What is testing.B.Loop (Go 1.24) and why is it preferred over the classic b.N loop?