Back to Concepts Roadmap
⚫ Level 6 — Memory Model
Memory Model
Stack vs Heap & Escape Analysis
How the compiler decides between fast automatic stack allocations and garbage-collected heap allocations.
Real-World Analogy (Mental Model)
“Stack memory is a pad of sticky notes on your desk: instant to write on, torn off and recycled the moment you finish. Heap is the long-term warehouse storage room.”
Key Concepts & Rules To Remember
- Stack allocations cost almost 0 CPU cycles and are cleaned up on function return.
- Heap allocations require Garbage Collector tracking.
- Compiler Escape Analysis (`go build -gcflags="-m"`) determines where memory lives.
Step-by-Step Code
1. Understanding Stack vs Heap & Escape Analysis
How the compiler decides between fast automatic stack allocations and garbage-collected heap allocations. In Go, stack vs heap & escape analysis is designed around clarity and high runtime efficiency.
example.goGo 1.24+
func makeOnStack() int {
x := 42
return x // Stack allocated (copied by value)
}
func makeOnHeap() *int {
x := 42
return &x // Escapes to Heap! (Pointer outlives function)
}Common Beginner Pitfalls & Mistakes
Mistake: Misusing stack vs heap & escape analysis without understanding its memory or concurrency semantics.
✅ Correct Way: Always follow standard Go idioms and verify with tests.
Self Assessment
Knowledge Check
Verify your understanding with these interactive practice questions.
Quizzes
Quick checks for understanding
Multiple-choice with inline explanations—expand to see why.
What is the primary concept behind Stack vs Heap & Escape Analysis?
Finished this lesson?
Mark it as complete to track your overall Go mastery.