Go Academy · Lesson

Stack vs Heap and Escape Analysis

How Go decides where to allocate memory

Lesson 1 of 413 steps

Stack vs Heap and Escape Analysis is a free Go Academy lesson on CoddyKit. This is lesson 1 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, and your progress syncs across the web and the CoddyKit app. The Go Academy course includes 4 lessons in total.

Stack allocation

Local variables that do not escape the function are allocated on the goroutine stack. Stack allocation is fast (just a pointer increment) and zero-cost to collect (stack frame is popped on return).

Heap allocation

Variables that escape to the heap are allocated with the Go allocator and tracked by the garbage collector. Heap allocation is slower and adds GC pressure.

What causes escape?

Common escape causes: taking the address of a local variable and returning it, storing a local in an interface, or sending it on a channel. The compiler's escape analysis determines this.

func newUser() *User { // *User escapes to heap
    return &User{Name: "Alice"}
}

go build -gcflags=-m

Print escape analysis decisions:

go build -gcflags="-m" .
// main.go:10:15: &User literal escapes to heap
// main.go:5:14: s does not escape

Goroutine stacks

Each goroutine starts with a small stack (2 KiB in Go 1.14+) that grows dynamically as needed. Stacks are separate from the heap and are collected when the goroutine exits.

Avoiding allocations

Pass values (not pointers) for small structs. Use stack-allocated arrays instead of slices where size is known. Return values instead of pointers to keep them on the stack.

Interface boxing

Assigning a concrete value to an interface causes the value to escape to the heap (boxing). For hot paths, accept concrete types or use generics instead of interfaces.

sync.Pool

Reuse heap-allocated objects with sync.Pool to reduce GC pressure from frequent allocations of short-lived objects (buffers, request contexts).

var pool = sync.Pool{New: func() any { return make([]byte, 1024) }}
buf := pool.Get().([]byte)
defer pool.Put(buf[:0])

Profiling allocations

Use go test -benchmem and heap profiling with -alloc_space to find the functions allocating the most memory.

slice vs array

A small array [N]T may stay on the stack. A slice header (24 bytes) is stack-allocated but its backing array may escape. Pre-allocating with make avoids repeated reallocation.

String interning

String literals are not heap-allocated (they are in the read-only data segment). Converting []byte to string allocates. Cache frequently used strings to avoid repeated conversions.

Quick Check

What causes a local variable to escape from the stack to the heap?

Recap: Stack vs Heap

Key points:

  • Stack: fast, zero-cost GC; Heap: slower, tracked by GC
  • go build -gcflags="-m" shows escape decisions
  • Interface boxing, address-of-local, channel sends cause escapes
  • sync.Pool for frequently allocated/discarded objects
Free to start

Learn Go with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
51
Lessons
203

Frequently Asked Questions

Is the “Stack vs Heap and Escape Analysis” lesson free?

Yes — any 3 lessons of the Go Academy learning path, including “Stack vs Heap and Escape Analysis”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Go Academy course includes 4 lessons in total.

What will I learn in “Stack vs Heap and Escape Analysis”?

How Go decides where to allocate memory You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 4.

How long does the “Stack vs Heap and Escape Analysis” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Stack vs Heap and Escape Analysis
  2. The Go Memory Model and Happens-Before
  3. Garbage Collector Internals
  4. Reducing Allocations: sync.Pool and Arenas
← Back to Go Academy