What is escape analysis in Go?

Answer

Escape analysis is a compile-time analysis that determines whether a variable can safely live on the goroutine's stack or must be heap-allocated. Stack allocation is vastly cheaper — it requires no GC, no synchronization, and is cache-friendly. If a variable's address is taken and passed to a function that stores it beyond the current stack frame, or if it is returned from a function, it "escapes" to the heap. Run go build -gcflags="-m" to see the compiler's escape decisions. Writing allocation-free hot paths (avoiding unnecessary heap escapes) is a key Go performance optimization. Common escapes: interface conversions, closures capturing variables, and values returned as pointers.