Stage 3 · Build
Performance, Memory & Debugging
Escape Analysis
Using go build -gcflags=-m to understand heap allocation and inlining decisions.
What Is Escape Analysis
Escape analysis determines whether variables are allocated on the stack or the heap. Stack allocation is fast — just moving a stack pointer. Heap allocation requires garbage collection. Understanding escape analysis helps you write faster, more memory-efficient code.
# Show escape decisions
go build -gcflags="-m" ./...
# Show more detail
go build -gcflags="-m -m" ./...
# For a specific package
go build -gcflags="-m" ./internal/cache
# Combine with other flags
go vet -gcflags="-m" ./...-m shows escape analysis decisions. -m -m shows more detail. The output tells you which variables escape to the heap and why. Use this to identify unnecessary allocations.
Compiler Flags
# Escape analysis
go build -gcflags="-m" ./...
# Disable inlining (simplifies escape analysis)
go build -gcflags="-m -l" ./...
# Show all optimization decisions
go build -gcflags="-m -m" ./...
# Disable optimizations (for debugging)
go build -gcflags="-N -l" ./...
# Race detector (shows allocation patterns)
go test -race ./...
# Assembly output (see stack vs heap)
go build -gcflags="-S" ./... | grep -E "(MOVUPS|LEAQ).*(SP|FP)"gcflags passes flags to the Go compiler. -m shows escape analysis. -l disables inlining. -N disables optimizations. -S shows assembly output. These flags help you understand what the compiler is doing.
Common Escape Reasons
Reducing Allocations
Inlining Decisions
Inlining replaces a function call with the function body. This eliminates call overhead and enables further optimizations. Small functions are inlined automatically.
Profiling Allocations
Do not optimize every function. Profile first, identify the hot path, and optimize the functions that appear in the top of the profile. Most programs spend 80% of time in 20% of the code.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.