The Analogy: The Desk and the Warehouse
You have a desk and the company has a warehouse. The desk is free: when you leave the room at the end of the visit, everything on it is swept away in one motion, and nobody has to decide what to keep. The warehouse costs money. Putting a crate in it means a clerk logs it, finds a space for it, and later has to walk the aisles working out which crates nobody references any more so they can be hauled out. Both storage places work. Only one of them has staff.
There is exactly one rule about the desk: nothing on it may be needed after you leave the room. If a colleague asks for a document and you hand them a note saying "third drawer of my desk", the note is worthless the moment your desk is cleared -- so that document cannot live on your desk. It has to go to the warehouse, where it will still exist when they come looking. Anything whose address travels further than the visit has to be stored somewhere that outlives the visit. That is the whole idea of escaping.
In Go you do not make this decision, and there is no keyword for it. new(T) does not mean heap and var t T does not mean stack; the compiler examines every value you create, works out whether any reference to it can outlive the function, and picks the cheaper place that is still correct. The analysis is deliberately one-sided: when it cannot prove a value stays local, it sends it to the warehouse. A compiler that guesses wrong toward the heap costs you performance; one that guessed wrong toward the stack would corrupt memory, so it never guesses that way.
This is why escape analysis is a performance topic and never a correctness topic. You cannot produce a dangling pointer in Go by returning the address of a local -- the compiler simply moves the local to the heap and the program is correct. What you can produce is a function that allocates on every call, in a loop that runs a million times a second, feeding a garbage collector that then has to walk everything you made. Reading the compiler's decisions is how you find out that you are paying warehouse rent for something that could have sat on the desk.
Syntax or Core Structure
The compiler will tell you what it decided if you ask. -gcflags=-m prints one line per decision for the packages you name; -gcflags=all=-m does it for every dependency too, which is almost always more output than you want.
// escape.go
package main
import "fmt"
type Point struct{ X, Y int }
// value returns a copy, so nothing needs to outlive the call.
func value() Point {
p := Point{1, 2}
return p
}
// pointer returns an address, so p has to survive the return.
func pointer() *Point {
p := Point{3, 4}
return &p
}
// read takes an address but only dereferences it.
func read(p *Point) int {
return p.X + p.Y
}
var kept *Point
// keep stores the address somewhere that outlives every call.
func keep(p *Point) {
kept = p
}
func main() {
a := value()
b := pointer()
c := Point{5, 6}
d := Point{7, 8}
keep(&d)
fmt.Println(a, *b, read(&c), kept.Y)
}
go run .
go build -gcflags=-m . 2>&1 | grep -v inlining
Output:
The program prints one line. The compiler's report is abbreviated below -- the inlining chatter is filtered out, and both the exact wording and the line numbers move between Go releases, so read it for the verbs rather than matching the text character by character.
{1 2} {3 4} 11 8
./escape.go:9:6: can inline value
./escape.go:15:6: can inline pointer
./escape.go:16:2: moved to heap: p
./escape.go:17:9: &p escapes to heap
./escape.go:21:6: can inline read
./escape.go:21:11: p does not escape
./escape.go:28:6: can inline keep
./escape.go:28:11: leaking param: p
./escape.go:36:2: moved to heap: d
./escape.go:38:13: ... argument does not escape
./escape.go:38:14: a escapes to heap
Four decisions, and they are the four you will meet for the rest of your career. pointer's local p was moved to heap because its address is returned. read's parameter does not escape, so c in main stayed on the stack even though its address was taken -- taking an address is not what costs you, letting the address travel is. keep is a leaking param, which is a statement about the function: it means every caller that passes an address is forced to allocate, which is why d was moved to the heap and c was not. And a escapes to heap at the fmt.Println call, because boxing a value into an any that fmt might hold on to needs somewhere durable to put it.
Technical Depth: What the Compiler Can and Cannot Prove
The messages, and what each one is about
| Message | What it is telling you |
|---|---|
moved to heap: x | A local variable is now a heap object. This is the expensive one. |
&x escapes to heap | The site where the address got away. Usually paired with a moved to heap. |
x escapes to heap | A value escaped here, most often by being boxed into an interface. |
x does not escape | The value or parameter stayed in the frame. This is the outcome you want. |
leaking param: p | A statement about your function: p itself outlives the call, so callers pay. |
leaking param content: p | Only what p points at leaks, not p. Common for slices, maps and interfaces. |
... argument does not escape | The backing array of a variadic call stayed on the stack, even if its elements did not. |
can inline f / inlining call to f | Not escape analysis, but it changes escape analysis. See below. |
What forces the heap
| Cause | Example |
|---|---|
| Returning the address of a local | return &p |
| Storing an address somewhere longer lived | a package variable, a field of a heap object, a map or slice element |
| Sending a pointer on a channel | ch <- &job |
A closure that outlives the call, including any go statement | go func() { use(x) }() |
| Boxing into an interface the callee may keep | fmt.Println(x), any(x), storing into an error field |
| Calling a function whose parameter is a leaking param | including most of fmt and anything taking any |
| A size not known at compile time | make([]byte, n) with a variable n |
| A local too large for a frame | currently around 10 MB for a declared var, 64 KB for an implicit allocation |
unsafe.Pointer arithmetic on the value | the compiler stops reasoning about it and assumes the worst |
Two of these are worth reading twice. A go statement is a closure that certainly outlives the function that started it, so every variable a goroutine touches is a candidate for the heap. And "a size not known at compile time" is why make([]byte, 4096) can sit in a frame while make([]byte, n) cannot: a stack frame's layout is fixed when the function is compiled.
The analysis is interprocedural, but an interface is a wall
Escape analysis is not confined to one function. The compiler computes a summary for each function -- which parameters leak, and to where -- and uses those summaries at every call site. That is why read(&c) costs nothing: the compiler had already concluded that read does not let p escape, and it propagates that fact to main.
The summary is keyed to a specific function, so anything that hides which function will run defeats it:
type Sink interface{ Take(*Point) }
func viaInterface(s Sink) {
p := Point{1, 2}
s.Take(&p) // which Take? the compiler often cannot know: p escapes
}
func viaConcrete(s *Discard) {
p := Point{1, 2}
s.Take(&p) // exactly one Take, and it does not leak: p stays
}
An interface method call, a call through a function value, and a call into a package compiled without inlining information all have the same effect: the compiler assumes the callee leaks everything and moves the value to the heap. Go does devirtualize some interface calls when it can prove the dynamic type, but you should not plan around it. If a hot path allocates for no visible reason, look for an interface between you and the work.
Inlining and escape analysis are entangled
The two passes feed each other. Inlining a small function copies its body into the caller, at which point the compiler is reasoning about real variables rather than a summary and can often prove more. The consequences are practical: a function that shows does not escape when inlined may allocate when it is not, and adding //go:noinline to "isolate" a benchmark can change the very thing you are measuring. If a decision surprises you, -gcflags='-m -m' prints the reasoning chain -- which assignment led to which -- and it is the only way to find out why something leaked rather than just that it did.
What the heap actually costs
A stack allocation is an offset in a frame that already exists: no bookkeeping at creation, and no work at all to release, because the frame goes away when the function returns. A heap allocation calls runtime.mallocgc, which picks a size class, possibly refills a span from the central lists, and zeroes the memory. Then the object joins the set the garbage collector has to trace, so you pay a second time during marking, and a write barrier is active on every pointer store while a collection is in progress. Heap objects are also scattered, so a hot loop over them misses cache in a way a stack frame does not.
Stack allocation is cheap, not free. A goroutine's stack starts small -- a couple of kilobytes -- and grows by allocating a bigger one and copying, adjusting every pointer into the old stack as it goes. A function with a very large frame, or deep recursion, triggers that copy, which is why moving a 100 KB array from the heap to a local is not automatically a win.
Working with it rather than against it
The techniques that reliably remove allocations are not tricks; they are API shapes:
- Return values, not pointers, for small structs. A
Pointis sixteen bytes. Copying it is two register moves; heap-allocating it is a function call plus future GC work. - Take a buffer from the caller. This is why the standard library has
strconv.AppendInt,time.Time.AppendFormatand(*bytes.Buffer).Writealongside their string-returning cousins. The caller owns the memory and can reuse it. - Pre-size.
make([]T, 0, n)allocates once instead oflog ntimes, and it is the difference between three allocations and twelve in the same function. - Keep
fmtandanyout of hot loops.strconvdoes the same work without boxing. - Reach for
sync.Poolonly for large, short-lived buffers, and only after measuring. It is not a general allocator, it can drop its contents at any collection, and keeping a reference to something afterPutis a data race waiting to be found in production.
Real World Example: A Log Line That Allocates Nothing
A structured logger formats the same line shape millions of times. Here are two implementations of one format, and the difference between them is entirely about where the bytes live.
// logfmt.go
package logfmt
import (
"fmt"
"strconv"
"time"
)
type Entry struct {
Level string
Msg string
Code int
Dur time.Duration
}
// Slow builds the line with fmt and hands back a fresh string.
func Slow(e Entry) string {
return fmt.Sprintf("level=%s code=%d dur=%dus msg=%q",
e.Level, e.Code, e.Dur.Microseconds(), e.Msg)
}
// Append writes into a buffer the caller owns and returns it. It creates
// nothing that outlives the call.
func Append(dst []byte, e Entry) []byte {
dst = append(dst, "level="...)
dst = append(dst, e.Level...)
dst = append(dst, " code="...)
dst = strconv.AppendInt(dst, int64(e.Code), 10)
dst = append(dst, " dur="...)
dst = strconv.AppendInt(dst, e.Dur.Microseconds(), 10)
dst = append(dst, "us msg="...)
dst = strconv.AppendQuote(dst, e.Msg)
return dst
}
The compiler's report, abbreviated to the escape decisions:
./logfmt.go:18:6: can inline Slow
./logfmt.go:18:11: leaking param content: e
./logfmt.go:19:20: ... argument does not escape
./logfmt.go:20:3: e.Level escapes to heap
./logfmt.go:20:11: e.Code escapes to heap
./logfmt.go:20:19: e.Dur.Microseconds() escapes to heap
./logfmt.go:20:44: e.Msg escapes to heap
./logfmt.go:25:6: can inline Append
./logfmt.go:25:13: leaking param: dst to result ~r0 level=0
Slow escapes four values and Append escapes none. ... argument does not escape tells you the variadic backing array itself stays on the stack, so the four escapes are the four boxed arguments, not the slice holding them.
A test pins the two implementations together, and a pair of benchmarks measures them:
// logfmt_test.go
package logfmt
import (
"testing"
"time"
)
var sample = Entry{
Level: "info",
Msg: "cache miss for user 4711",
Code: 200,
Dur: 1500 * time.Microsecond,
}
func TestSameLine(t *testing.T) {
const want = `level=info code=200 dur=1500us msg="cache miss for user 4711"`
if got := Slow(sample); got != want {
t.Errorf("Slow:\n got %s\n want %s", got, want)
}
if got := string(Append(nil, sample)); got != want {
t.Errorf("Append:\n got %s\n want %s", got, want)
}
}
func BenchmarkSlow(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
Slow(sample)
}
}
func BenchmarkAppend(b *testing.B) {
buf := make([]byte, 0, 128)
b.ReportAllocs()
for b.Loop() {
buf = Append(buf[:0], sample)
}
}
Output (one particular laptop; the allocation columns are the part that transfers):
BenchmarkSlow-8 4173820 285.6 ns/op 104 B/op 4 allocs/op
BenchmarkAppend-8 14268914 84.12 ns/op 0 B/op 0 allocs/op
The 104 bytes are itemised, and the itemisation is the whole lesson. Boxing e.Level into an any costs a 16 byte string header on the heap, and boxing e.Msg costs another 16. Boxing the int64 microsecond count costs 8. The returned line is 61 bytes, which the allocator rounds up to the 64 byte size class. That is 16 + 16 + 8 + 64 = 104. What is missing is a box for e.Code: the runtime keeps a static table of the integers 0 through 255, so boxing 200 hands back a pointer into that table instead of allocating. Change Code to 4711 and the same benchmark reports 5 allocs/op and 112 B/op. That is a prediction you can check in about thirty seconds, and checking it is worth more than taking my word for it.
Append reports leaking param: dst to result ~r0, and that is the harmless kind of leak. The compiler is recording an ownership fact - whatever the caller passed in may come back out - not a cost. Nothing new reaches the heap, because the memory was already the caller's. That is precisely why the shape works: the benchmark's buf is allocated once with make([]byte, 0, 128), and buf[:0] rewinds the length to zero on every iteration while keeping the capacity. Sixty one bytes never exceeds 128, so append never grows and never reallocates. Compare that with keep's leaking param: p from earlier in this lesson, where the leak forced its caller's local to the heap. Same verb, opposite consequence, and the to result suffix is how you tell them apart.
Removing four allocations bought a 3.4x speed-up, which is more than mallocgc alone would explain. The rest comes from the work that surrounds the allocations: fmt.Sprintf walks the format string one verb at a time, dispatches through an interface for each argument, and copies the finished bytes into a fresh string. Append does none of that - it is a handful of memmove calls into memory that is already hot in cache. And the allocation count keeps costing after the function returns, because every object the collector never sees is scanning work it never does. A service writing 50,000 log lines a second at 4 allocs per line hands the garbage collector 200,000 objects a second purely to describe events it has already written.
Two cautions to leave with. First, Slow is the more readable function, and readability is the default; you reach for the Append shape after a profile has named this function, not before. A CLI that prints one line does not need it. Second, keep TestSameLine. The moment the two implementations disagree - a missing space, a quoting difference, a duration unit that drifted - the fast one silently corrupts your logs. This is the same discipline as the benchmarking lesson's TestBothAgree, and it matters more here, because the reward for getting the fast path wrong is a log file nobody can parse.
Common Mistakes
- Believing
new(T)means heap andT{}means stack. The two are the same to escape analysis.p := new(int); *p = 3; return *pkeepspon the stack, andx := T{}; return &xmovesxto the heap. The keyword tells you nothing; the flow of the pointer tells you everything.
- Returning a pointer "to avoid copying the struct". Returning
*Pointforces a heap allocation and then makes every field read an indirection. ReturningPointcopies sixteen bytes in registers. For small structs the value is faster and generates less garbage. Measure before you assume a copy is the expensive part.
- Running
-gcflags=-mand reading the flood. Bare-gcflags=-mreports on your package.-gcflags=all=-mreports on every package in the build including the standard library, which is thousands of lines. Start narrow, and pipe throughgrep -v inliningwhen you only care about escapes.
- Reading the report for a function that was inlined away. Once a call is inlined, the escape decision belongs to the caller's frame, and the callee's own
does not escapeline may no longer describe the program that runs. If the numbers and the report disagree, check forcan inlinefirst.
- Ignoring
leaking paramin your own exported API. A setter that stores its argument in a struct field is a leak by design, and every caller pays for it forever. It is often the right design, but it should be a decision rather than an accident, and it belongs in the doc comment.
- Calling
fmtin a hot loop.fmt.Sprintf,fmt.Errorfandlog.Printfbox every argument into anany, and each box that outlives the call is an allocation. In code that runs a million times a second, reach forstrconvandstrings.Builderinstead.
- Assuming a slice of pointers is cheaper than a slice of values.
[]*Itemis N allocations plus a slice the collector must scan pointer by pointer.[]Itemis one allocation, and ifItemcontains no pointers the collector can skip scanning it entirely. Pointers earn their place when the elements are large or genuinely shared.
- Switching a method to a pointer receiver "for performance" without measuring. A pointer receiver can force the value to the heap where a value receiver would not have. The receiver kind is a semantic choice - does the method mutate, is the type copyable - and the performance argument only applies once the struct is genuinely large.
- Reaching for
sync.Poolat the first sign of an allocation. A pool adds bookkeeping, is cleared at every garbage collection, and can hold on to memory you wanted released. It pays for large, short-lived buffers with a clear reset point. It does not pay for a sixteen byte struct.
- Chasing escapes without watching
allocs/op. The report is a static prediction; the benchmark is the measurement. Restructure the code, rerun the benchmark, and ifallocs/opdid not move you have made the code harder to read for nothing. Revert it.
- Forgetting that an interface method call blocks the analysis. Passing
*bytes.Bufferto a parameter typedio.Writermeans the compiler cannot see whichWriteruns, so it assumes the worst. If a hot path must not allocate, give it the concrete type and let the interface live at the boundary.
Best Practices
- Treat escape analysis as a performance tool only. Go's memory safety does not depend on it, and no report can make a program incorrect.
- Reach for the report when a benchmark has already shown you a bad
allocs/op. Working the other way round - reading reports looking for something to fix - burns time on allocations that never mattered.
- Prefer returning values for small structs and reserve pointers for large ones, for mutation, and for genuine sharing.
- Offer an
Append(dst []byte, ...) []byteform alongside any string-returning formatter in a hot path. The standard library does this everywhere, fromstrconv.AppendInttotime.Time.AppendFormat.
- Pre-size with
make(T, 0, n)whenever you know or can estimaten. One right-sized allocation beats a growth sequence, and it costs one argument.
- Keep
anyandfmtout of the innermost loop. Move formatting to the edge of the system where it happens once per request rather than once per row.
- Use concrete types on hot paths and interfaces at package boundaries. The wall the interface builds is the reason a design that reads beautifully can allocate on every call.
- Verify with
-benchmem, and readallocs/opbeforens/op. The allocation count is stable across machines; the nanoseconds are not.
Practice Exercises
- Write six one-line functions - returning a value, returning a pointer, taking a pointer and only reading it, storing a pointer in a package variable, putting a value into an
any, and closing over a local - and write down your prediction for each before you run anything. Then rungo build -gcflags=-m .and score yourself. Every prediction you got wrong is a rule you did not actually hold.
- Take a function whose report says
leaking param: pand change its signature so the report saysp does not escapeinstead, without changing what the function achieves. Usually this means copying what you need out of the argument rather than keeping the pointer. Then write a benchmark that proves the caller's allocation went away.
- Convert one
fmt.Sprintfin real code into anAppend-style function with a caller-owned buffer. Benchmark both with-benchmem, then change one small integer argument from a value under 256 to a value over 255 and explain the extra allocation that appears.
- Find the size at which the compiler stops keeping a local array on the stack. Write
func f(n int) intvariants declaringvar buf [N]bytefor N of 1024, 16384, 65536 and 131072, returnlen(buf), and read the report each time. Then explain why an array whose size comes from a variable rather than a constant escapes at every size.