Escape analysis is a compiler analysis that determines where a variable lives: stack or heap.
1// Escape analysis2go build -gcflags="-m" ./...34// Example: variable "escapes" to heap5func foo() *int {6 x := 42 // "moved to heap: x"7 return &x // Returned by pointer8}910// Example: variable stays on stack11func bar() int {12 x := 42 // Stays on stack13 return x14}1516// Example: interface{} sends to heap17func process(v interface{}) {18 // v lives on heap19}2021func main() {22 x := 4223 process(x) // x "escapes" to heap24}2526// Example: closure captures a variable27func create() func() int {28 x := 029 return func() int {30 x++ // x lives on heap31 return x32 }33}3435// Optimization: avoid leaks36// Bad:37func getData() []byte {38 buf := make([]byte, 1024)39 return buf // Escapes to heap40}4142// Good:43func getData(buf []byte) {44 // buf is passed by reference, not copied45}4647// Memory analysis48func benchmarkMemory() {49 var stats runtime.MemStats50 runtime.ReadMemStats(&stats)51 fmt.Printf("HeapAlloc: %d MB\n", stats.HeapAlloc/1024/1024)52 fmt.Printf("NumGC: %d\n", stats.NumGC)53}
Performance impact: