Stack vs Heap and Escape Analysis
How Go decides where to allocate memory
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.
All lessons in this course
- Stack vs Heap and Escape Analysis
- The Go Memory Model and Happens-Before
- Garbage Collector Internals
- Reducing Allocations: sync.Pool and Arenas