Go Escape Analysis and Stack versus Heap Allocation
Go’s escape analysis is a compiler analysis that decides whether a value can safely live in a goroutine’s stack frame or must be allocated on the heap. A value stays on the stack when the compiler can prove it will not be used after the function or stack frame ends; otherwise, its storage escapes to the heap.
That decision is made at compile time. It is not a runtime switch and it is not controlled directly by whether you wrote new or &.
The problem escape analysis solves
A stack allocation is naturally temporary. When a function returns, its stack frame can be discarded, so allocating local variables there is fast and requires no individual garbage-collector bookkeeping. The stack is also private to the goroutine while the function runs.
Heap storage has a longer lifetime. It remains valid after the creating function returns and can be shared by other goroutines or by other parts of the program. But heap allocations add work: the allocator must obtain storage, and the garbage collector may later need to find and reclaim it. Heap objects can therefore increase allocation rate, GC work, memory use, and latency.
Without escape analysis, a compiler would have to put every value whose address is taken on the heap, even when the address is used only inside the current function. That would make ordinary code such as this unnecessarily expensive:
func sum() int {
x := 10
p := &x
return *p + 5
}
Although x has an address, p never survives sum. The compiler can keep x in the stack frame—or optimize the calculation further—because no later operation can observe an invalid address.
What the compiler follows
The compiler tracks how values and pointers flow through the program. It asks a practical question: can a reference to this storage reach a place that outlives the current stack frame? If yes, the storage must be heap-backed.
A straightforward example is returning a pointer to a local variable:
func newCounter() *int {
count := 0
return &count
}
After newCounter returns, its stack frame is gone. The returned pointer must still work, so count is allocated on the heap. The source code still declares count as a local variable; “moving to the heap” describes the compiler’s chosen storage, not a source-level operation performed at runtime.
Passing a pointer to a function does not automatically make it escape. The result depends on what the called function can do with it:
func increment(p *int) {
*p++
}
func total() int {
n := 1
increment(&n)
return n
}
Here, increment only uses the pointer during the call and does not retain it. With the relevant compiler information available, n can remain on the stack. If a called function stores the pointer globally, returns it, puts it into an object that outlives the call, or starts work that may use it later, the pointed-to storage must instead be safe after the caller returns.
The same rule applies when the pointer is hidden inside another value. Returning a slice, for example, returns a descriptor containing a pointer to an underlying array:
func bytesForMessage() []byte {
message := []byte("hello")
return message
}
The result must refer to valid bytes after bytesForMessage returns, so the backing array cannot be only part of that function’s stack frame. It needs storage with a longer lifetime, normally the heap.
Closures create another common path. A closure is a function value that carries variables from its surrounding scope. If the closure runs after the surrounding function returns, captured variables need storage that remains valid:
func counter() func() int {
n := 0
return func() int {
n++
return n
}
}
The returned function still needs n, so n escapes. Starting a goroutine with a closure is a similar case when the goroutine may outlive the current function.
How the analysis makes the decision
Escape analysis is based on conservative compile-time reasoning. The compiler builds information about assignments, address-taking, returns, captured variables, and calls. It also uses summaries for functions so that it can understand whether arguments are retained or only used during a call. The analysis runs across function boundaries where the compiler can inspect or summarize the relevant code.
“Conservative” matters: if the compiler cannot prove that a pointer stays within the current lifetime, it treats the value as escaping. It does not run the program to see what happens on a particular input. An indirect call, a value passed through an interface, or complicated aliasing can make that proof harder, so apparently similar code can produce different results.
Taking an address, using an interface, or returning a value is therefore not a universal rule by itself. The decisive issue is the possible lifetime and reachability of the storage. A value can be returned by value and still be inexpensive if the compiler copies or keeps it in registers; a small local value can escape if a surviving reference to it is created.
Seeing the compiler’s reasoning
The compiler can print escape decisions during a build. For example:
go build -gcflags=-m=2 ./...
The output includes messages such as x escapes to heap and explanations of the flow that caused the decision. The exact wording varies between Go releases, so treat it as diagnostic output rather than a stable interface. The -gcflags option is useful for investigation, but it is not normally something to add to production builds.
What it means for performance
Stack-resident values generally avoid a heap allocation and reduce pressure on the garbage collector. That can improve throughput and tail latency, especially in allocation-heavy paths such as request handling or serialization. Heap allocation is not automatically slow, and the compiler may eliminate or simplify allocations in other optimization passes, but unnecessary escaping can become visible in profiles and benchmarks.
Use allocation measurements rather than guessing. go test -bench can report allocations with -benchmem, and runtime or profiling tools can show allocation hot spots. A benchmark should also consume its result; otherwise the compiler may remove work that the benchmark intended to measure.
Finally, do not contort an API solely to avoid every escape. Returning a pointer may be the clearest design, and a real shared lifetime may require the heap. Escape analysis is the compiler’s way to make the safe choice automatically: keep storage on the goroutine stack when its lifetime is provably local, and use the heap when other code could still reach it later.