Go: Introduction to the Escape Analysis

Vincent
A Journey With Go
Published in
5 min readAug 6, 2020

--

Illustration created for “A Journey With Go”, made from the original Go Gopher, created by Renee French.

ℹ️ 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:

Abstract Syntax Tree of the source code

--

--