Learn

Escape analysis without the folklore

What the compiler actually decides when a value lives on the stack vs the heap — and how to read the evidence.

Escape analysis without the folklore

"Does this allocate?" is the wrong first question. Better: where must this value live so every reference stays valid?

Stack when you can

If a value's lifetime is strictly nested inside a function frame, and no reference escapes that frame, the compiler can keep it on the stack. No GC pressure, better locality, cheaper creation.

Heap when you must

A value escapes when a reference might outlive the frame — returned pointers, stored into longer-lived structures, closed over by a longer-lived function, or passed into interfaces in ways the compiler cannot prove safe.

How to verify

Folklore ("interfaces always allocate") is stale. Prefer evidence:

go build -gcflags='-m=2' ./...

Read the escape notes, then confirm with benchmarks or pprof alloc profiles under real load. Optimize the hot path you measured — not every interface conversion in the codebase.

Takeaway

Escape analysis is a proof problem, not a style rule. Write clear code first; use compiler output when allocation cost shows up in profiles. That habit transfers across languages and runtimes.