Inspect escape analysis and stack versus heap
Inspect escape analysis and stack versus heap
Escape analysis is a compiler analysis of whether a value can outlive its current frame or be referenced where stack storage is unsafe. A value that escapes may require heap storage; size, dynamic allocation and optimization also influence placement. Taking an address alone is not proof of a heap allocation. Go guarantees safe lifetimes for ordinary pointers, not the storage location. Inspect compiler diagnostics and measure allocations for the actual build.
package main
import ( "fmt")
//go:noinlinefunc makeValue(n int) *int { x := n + 1; return &x }
//go:noinlinefunc local(n int) int { x := n + 1; p := &x; return *p }func main() { fmt.Println(*makeValue(4), local(4))}Run go build -gcflags="-m=2" -o demo main.go. For this non-inlined build, inspect the moved-to-heap message for x in makeValue and compare local. Returning a pointer is safe; the compiler handles storage. With inlining, a different caller can avoid an allocation. Diagnostics are not portable assertions across versions.
Expected output:
5 5Measure an allocation difference
package main
import ( "fmt" "testing")
var sink *intvar result int
//go:noinlinefunc publish(n int) *int { return &n }
//go:noinlinefunc add(n int) int { return n + 1 }func main() { a := testing.AllocsPerRun(100, func() { sink = publish(3) }) b := testing.AllocsPerRun(100, func() { result = add(3) }) fmt.Println(a > b, *sink, result)}AllocsPerRun performs a warm-up and measures average heap allocations over repeated calls, temporarily setting GOMAXPROCS to 1. The global sinks prevent the example from becoming unused. This comparison is expected on the checked compiler, not a language guarantee. A count does not measure bytes, latency or retained heap. Use benchmarks with -benchmem for broader evidence.
Expected output:
true 3 4Try it locally
Compare two functions returning the same numeric result, one returning a pointer saved in a global, the other returning a value saved in a global. Use AllocsPerRun and print whether the pointer path allocates more on your compiler.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime allocation 03: Inspect escape analysis and stack versus heap
Check the lesson objective before moving on.
Does taking &x always cause heap allocation?
What does AllocsPerRun measure?