Escape analysis and allocations

The compiler decides for every value whether it lives on the stack or the heap. A value whose address leaves the function, or that is stored in an interface, escapes to the heap and costs an allocation and a garbage-collection cycle later. -gcflags=-m prints the decision, and testing.AllocsPerRun counts the result, which are the two measurements this lesson uses.

What escapes to the heap

The program has two functions that look alike: one returns a pointer to its local and one returns the value. The report says the local of the pointer function is moved to the heap, and the value function is inlined and its local stays where it is. The two prints at the end also allocate, because a string in an interface escapes.

package main import "fmt" type Point struct { X int Y int } func byPointer() *Point { p := Point{X: 1, Y: 2} return &p } func byValue() Point { p := Point{X: 3, Y: 4} return p } func main() { p := byPointer() v := byValue() fmt.Println("pointer:", p.X, p.Y) fmt.Println("value:", v.X, v.Y) }

go build -o app main.go && ./app

pointer: 1 2
value: 3 4

go build -gcflags=-m main.go 2>&1

# command-line-arguments
./main.go:10:6: can inline byPointer
./main.go:15:6: can inline byValue
./main.go:21:16: inlining call to byPointer
./main.go:22:14: inlining call to byValue
./main.go:23:13: inlining call to fmt.Println
./main.go:24:13: inlining call to fmt.Println
./main.go:11:2: moved to heap: p
./main.go:23:13: ... argument does not escape
./main.go:23:14: "pointer:" escapes to heap
./main.go:23:27: p.X escapes to heap
./main.go:23:32: p.Y escapes to heap
./main.go:24:13: ... argument does not escape
./main.go:24:14: "value:" escapes to heap
./main.go:24:25: v.X escapes to heap
./main.go:24:30: v.Y escapes to heap

The local p of byPointer moved to the heap because its address is the result; the local of byValue was inlined and stayed cheap. The string arguments to Println escape because the variadic call boxes them into interfaces, which is a cost of the print rather than of the struct.

String concatenation against a builder

Each s += "x" allocates a new string and copies the old one, so a loop of ten allocates nine times. A strings.Builder grows one buffer and copies once at the end, and the program below counts the allocations of each with testing.AllocsPerRun, which runs the function often enough to average out the noise.

package main import ( "fmt" "strings" "testing" ) func concat(n int) string { s := "" for i := 0; i < n; i++ { s += "x" } return s } func builder(n int) string { var b strings.Builder for i := 0; i < n; i++ { b.WriteString("x") } return b.String() } func main() { concatAllocs := testing.AllocsPerRun(100, func() { _ = concat(10) }) builderAllocs := testing.AllocsPerRun(100, func() { _ = builder(10) }) fmt.Println("concat allocations:", concatAllocs) fmt.Println("builder allocations:", builderAllocs) }

go build -o app main.go && ./app

concat allocations: 9
builder allocations: 2

Nine allocations for nine appends and one more for the result, against two for the builder: the buffer and the string it returns. The builder is the right tool in a loop, and a strings.Join over a slice is better still when the pieces are already collected, because it allocates one string and nothing else.

A slice with and without capacity

append grows a slice by allocating a bigger array and copying when the capacity runs out, so a loop that appends a hundred values to an empty slice reallocates about five times. A slice made with the capacity up front allocates once and never copies. The count below is the whole difference.

package main import ( "fmt" "testing" ) func grow(n int) []int { s := make([]int, 0) for i := 0; i < n; i++ { s = append(s, i) } return s } func growPrealloc(n int) []int { s := make([]int, 0, n) for i := 0; i < n; i++ { s = append(s, i) } return s } func main() { growAllocs := testing.AllocsPerRun(100, func() { _ = grow(100) }) preallocAllocs := testing.AllocsPerRun(100, func() { _ = growPrealloc(100) }) fmt.Println("grow allocations:", growAllocs) fmt.Println("prealloc allocations:", preallocAllocs) }

go build -o app main.go && ./app

grow allocations: 5
prealloc allocations: 0

Five reallocations against none, and the second also copies less. The zero is not always reachable: the count is zero because the compiler kept the preallocated slice on the stack and the function returns nothing that outlives it. A function that returns the slice pays one allocation, which is still the minimum for a value that escapes.

Fewer allocations, not zero

An allocation is not a bug. The rule is to remove the ones in a loop or on a request path that a profile shows, and to leave the rest alone: a clearer program with one more allocation is usually the better program. The tools to find the ones that matter are the escape report for a function, a benchmark with -benchmem, and the heap profile, in that order.

Three habits cover most of it. Reserve the capacity of a slice or a map when the size is known. strings.Builder instead of concatenation in a loop. And return a value rather than a pointer when the value is small and the caller does not need to share it. The next lesson is the collector that cleans up whatever still reaches the heap.

Exercises

  1. Return the struct by pointer from byValue and run the escape report again. Which line moves to the heap, and which inlining stops?
  2. Call b.Grow(10) before the loop in the builder and count again. How many allocations is the builder down to, and why not zero?
  3. Append a thousand values with and without capacity and compare the two counts. How many reallocations did the growth algorithm save?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does -gcflags=-m print?

    Answer

    The compiler's inlining and escape decisions

    It is the report this lesson reads.

  2. When does a value move to the heap?

    Answer

    When its address or an interface outlives the function

    The report says moved to heap.

  3. Why does a printed string escape?

    Answer

    The variadic call boxes it into an interface

    It is a cost of the print, not of the data.

  4. What does s += "x" do in a loop?

    Answer

    Allocates a new string and copies the old one each time

    A Builder is the loop tool.

  5. How many allocations does a Builder of ten pieces take here?

    Answer

    Two: the buffer and the result

    Grow can bring it to one.

  6. What does make([]int, 0, n) change?

    Answer

    The capacity, so append does not reallocate

    One allocation instead of log n.

  7. Why is the preallocated count zero?

    Answer

    The slice stays on the stack and does not escape

    A returned slice costs one allocation.

  8. When is an allocation worth removing?

    Answer

    When a profile shows it on a hot path

    Clarity is also a cost.

  9. Which benchmark flag counts allocations?

    Answer

    -benchmem

    It reports allocs/op and B/op.

  10. Which is cheaper for a small struct the caller does not share?

    Answer

    Return it by value

    A pointer makes it escape.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image