Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 147 ยท Pointers and Memory

Stack, Heap and Escape Analysis

Learn where Go values live, how the compiler decides between stack and heap with escape analysis, how to read -gcflags=-m output, and how to measure and reduce allocations.

When your Go program creates a value, that value has to live somewhere. There are two places: the stack, a fast region tied to a function call that vanishes when the call returns, and the heap, a larger region managed by the garbage collector. Unlike C, you do not choose. There is no "stack" or "heap" keyword in Go. The compiler decides for every variable, using a technique called escape analysis.

You can write correct Go without ever thinking about this. But when a program is slow or uses too much memory, knowing why a value ended up on the heap, and how to measure it, is a valuable skill. This lesson explains the two regions, the rules the compiler follows, how to read its report, and how to count allocations in code you can run right here. It builds on pointers and pointers with functions.

The stack and the heap

The stack. Each goroutine has its own stack. Calling a function reserves a block ("frame") for its parameters and local variables; returning from the function releases it. Allocating and freeing this way costs almost nothing: it is just moving a pointer. Go stacks start small (a few kilobytes) and grow automatically as needed, so deep recursion is fine:

Go Go stacks grow on demand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The heap. Values that must outlive the function that created them, or whose size is not known at compile time, go on the heap. Heap allocation is slower than the stack: the runtime must find space, and later the garbage collector must find and free it. Many small heap objects also mean more work for the GC and worse CPU cache behavior.

Neither region is "better". Stack allocation is cheaper, so the compiler prefers it whenever it can prove it is safe.

What escape analysis decides

For each variable, the compiler asks: can this value still be referenced after the function that declared it returns? If the answer is no, it stays on the stack. If it might be, or the compiler cannot prove it, the value escapes to the heap.

A variable typically escapes when:

  • its address is returned or stored somewhere that outlives the function (a field of a longer-lived struct, a global variable, a channel);
  • it is converted to an interface (such as any) and the compiler cannot show the interface does not escape. Calls like fmt.Println(x) often do this;
  • it is captured by a closure that escapes;
  • its size is unknown at compile time (make([]int, n) with a variable n) or very large;
  • a pointer to it is passed to a function the compiler cannot analyze, such as a call through an interface or a function value.

What does not make a variable escape: taking its address, using pointers within the function, or passing a pointer down to functions that do not keep it. Pointers are not "heap" by themselves.

Escape analysis is an implementation detail. Different Go versions (and different surrounding code) can make different decisions, and the language guarantees nothing about it. Your code is correct either way. Use this knowledge for diagnosing performance, never for correctness.

Reading -gcflags=-m output

The compiler can explain its decisions. Build with -gcflags=-m (add more ms for more detail) and it prints one line per decision. Here is a small file; the //go:noinline comments stop the compiler from merging the functions into main, which would hide the effects:

Go
package main

type Point struct{ X, Y int }

//go:noinline
func sumLocal() int {
	p := Point{1, 2}
	return p.X + p.Y
}

//go:noinline
func newPoint() *Point {
	p := Point{3, 4}
	return &p
}

//go:noinline
func fixedBuffer() int {
	buf := make([]byte, 64)
	return len(buf)
}

//go:noinline
func dynamicBuffer(n int) []byte {
	return make([]byte, n)
}

//go:noinline
func box(v int) any {
	return v
}

func main() {
	sumLocal()
	newPoint()
	fixedBuffer()
	dynamicBuffer(10)
	box(1)
}

Building it on your machine with the flag (this is the real output of go build -gcflags=-m main.go, not something our in-browser runner prints):

Terminal
$ go build -gcflags=-m main.go
# command-line-arguments
./main.go:13:2: moved to heap: p
./main.go:19:13: make([]byte, 64) does not escape
./main.go:25:13: make([]byte, n) escapes to heap
./main.go:30:9: v escapes to heap

Reading it line by line:

  • main.go:13:2: moved to heap: p is the p in newPoint, because the function returns &p. The variable has to outlive the call, so the compiler allocates it on the heap.
  • make([]byte, 64) does not escape means the 64-byte buffer stays on the stack. The size is a constant and the slice is only used locally.
  • make([]byte, n) escapes to heap is the buffer in dynamicBuffer: the size is a variable, and the slice is returned.
  • v escapes to heap is v stored into an any. The interface holds a pointer to a copy of the value, and since the interface is returned, that copy must live on the heap.
  • sumLocal does not appear at all: p never leaves the function, so there is nothing to report. No news is good news.

If you build without //go:noinline, you will also see lines like can inline sumLocal and inlining call to .... Inlining copies a small function's body into its callers and often removes allocations altogether, which is one reason results vary.

Measuring allocations with testing.AllocsPerRun

Guessing is unreliable, so measure. The testing package's AllocsPerRun(runs, f) calls f many times and returns the average number of heap allocations per call. It works in an ordinary main program, not just inside tests. We use package-level "sink" variables so the compiler cannot throw away our work.

Go Counting allocations per call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The struct that stays local costs nothing; the one whose pointer is stored in a global costs one allocation. Converting a changing int to any costs one allocation too, because the interface needs somewhere to keep the number. (Small constant values and tiny integers are special-cased by the runtime, which is why we make n change on every call.) The small fixed-size slice that never leaves the function is stack allocated.

Avoiding allocations

Most programs do not need to hunt allocations. But in hot paths such as parsers, servers and loops that run millions of times, a few habits matter:

  1. Preallocate slices and maps when you know the size: make([]T, 0, n).
  2. Use strings.Builder instead of s += part in a loop. Each += allocates a new string.
  3. Reuse buffers with buf[:0] and the Append functions (strconv.AppendInt, fmt.Appendf) instead of creating new strings and byte slices.
  4. Avoid needless pointers and interfaces for small values. A []Point is one allocation, a []*Point is one per element plus the slice.
  5. Pass pointers only when you need sharing or mutation, not as a speed trick.
Go Allocation counts: growing, preallocating, concatenating

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Exact numbers depend on the Go version and its optimizer (older versions would report more allocations for growing), but the ordering stays the same: preallocating beats growing, and a builder beats repeated concatenation.

Reusing a buffer can take a function down to zero allocations:

Go Reusing a buffer with Append functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The reusable version writes into the same backing array every time; only the first call needs memory.

Do not optimize allocations before you have a reason. Readable code that allocates is better than clever code that does not, until a profile (go test -bench -benchmem, or pprof) shows the allocations are your bottleneck. Measure first, change second, measure again.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Who decides whether a Go local variable lives on the stack or the heap?

    Neither new nor make nor & decides placement. The compiler checks whether the value can outlive its function and moves it to the heap only if it can.
  2. 2. In func f() *int { x := 1; return &x }, where does x live?

    The address outlives the call, so the compiler reports that x was moved to the heap. This is safe in Go.
  3. 3. What does the line make([]int, 8) does not escape mean?

    The phrase "does not escape" means the value never leaves the function, so it can be stack allocated and needs no garbage collection.
  4. 4. Why is s += part inside a long loop usually slower than using strings.Builder?

    Strings are immutable, so every concatenation allocates a new string and copies the old content. A builder appends into one growing buffer.
  5. 5. What does testing.AllocsPerRun(100, f) return?

    It runs f repeatedly and returns the average count of heap allocations per run, as a float64.

Summary

  • The stack is fast, per-goroutine and grows automatically; the heap is managed by the garbage collector and costs more to allocate and to clean up.
  • You never choose: the compiler's escape analysis keeps a value on the stack unless it might outlive its function (returned or stored pointers, interface conversion, escaping closures, unknown sizes).
  • go build -gcflags=-m reports the decisions, with lines like moved to heap: p and does not escape.
  • testing.AllocsPerRun measures heap allocations per call in an ordinary program.
  • Cut allocations in hot code with preallocation, strings.Builder, reusable buffers and fewer needless pointers, but only after measuring.

Next: Garbage Collection and Memory