Memory Management & Garbage Collection
Memory Management & Garbage Collection in V8
JavaScript automatically manages memory allocation and deallocation through an automated Garbage Collector (GC). However, high-throughput backend services and complex client applications can suffer severe latency spikes ("Stop-the-World" pauses) if developers write code that fights V8's memory management engine.
1. The V8 Memory Lifecycle: Allocation, Usage, Release
- Stack Memory: Stores primitive values (
number,boolean,symbol) and references/pointers. Super fast allocation and deallocation (LIFO). - Heap Memory: Stores dynamic, complex objects (
objects,arrays,functions, closures). Managed by the Garbage Collector.
2. Reachability & The Mark-and-Sweep Algorithm
Modern JavaScript engines use the Mark-and-Sweep algorithm based on the concept of Reachability:
- A value is reachable if it is accessible directly or indirectly from a Root (Global
window/global, local variables in current call stack). - Mark Phase: The GC traverses the object graph starting from roots, marking every visited object as "alive".
- Sweep Phase: Any un-marked memory is swept and returned to the free list.
3. V8 Generational Garbage Collection
V8 divides the Heap into two main generations based on the Weak Generational Hypothesis ("Most objects die young"):
- 1Young Generation (Minor GC / Scavenger): Uses a two-semi-space copying collector. Very fast (~1ms). Most temporary objects are destroyed here.
- 2Old Generation (Major GC / Full Mark-Sweep): Objects that survive multiple young cycles are promoted to the Old Generation. Major GC runs less frequently, using incremental and concurrent marking to minimize UI freeze pauses.
4. Avoiding GC Pauses: Object Pooling
In high-performance gaming or real-time trading engines, creating thousands of temporary objects per second causes frequent Minor GC pauses. Object Pooling reuses pre-allocated objects instead of creating new ones:
Practice Quiz
Core Web Vitals & JavaScript Impact
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| requestAnimationFrame & Smooth Animations | Core Web Vitals & JavaScript Impact |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.