Go: Introduction to the Escape Analysis
ℹ️ This article is based on Go 1.13.
The escape analysis one of the phases of the Go compiler. It analyses the source code and determines what variables should be allocated on the stack and which ones should escape to the heap.
Static analysis
Go statically defines what should be heap or stack-allocated during the compilation phase. This analysis is available via the flag -gcflags="-m"
when compiling and/or running your code thanks to go run
or go build
. Here is a simple example:
func main() {
num := getRandom()
println(*num)
}
//go:noinline
func getRandom() *int {
tmp := rand.Intn(100)
return &tmp
}
Running the escape analysis shows us tmp
escapes to the heap:
./main.go:12:2: moved to heap: tmp
The first step of the static analysis is building the Abstract Syntax Tree of the source code, allowing Go to understand where assignments and allocations are done along with variables addressing and dereferencing. Here is an example of the previous code: