How Escape Analysis Works in Go

Go's escape analysis determines at compile time if variables stay on the stack or move to the heap to optimize memory usage.

Escape analysis in Go determines at compile time whether a variable must be allocated on the heap or can remain on the stack. The compiler performs this analysis during the middle-end optimization phase in cmd/compile/internal/escape to minimize garbage collection overhead. You can inspect the compiler's decisions by running your build with the -m flag:

go build -m -gcflags="-m" main.go

This outputs lines like can inline or escaping to heap explaining why specific variables were promoted to the heap.