Memory Management and Garbage Collection (V8)
V8 Memory Management & Garbage Collection
High-performance Node.js requires a deep understanding of how the V8 engine partitions memory into the Stack (for primitives and call frames) and the Heap (for complex objects).
The Generational Hypothesis
V8 assumes that most allocated objects die young. Therefore, the Heap is bifurcated:
- New Space (Scavenger): A small, fast memory sector where objects are born. The Scavenger GC runs frequently, swiftly clearing short-lived objects.
- Old Space (Mark-Sweep-Compact): Objects that survive multiple Scavenger cycles are promoted to Old Space. The Major GC traverses these objects periodically, pausing execution slightly (Stop-The-World) to sweep dead memory and defragment.
Identifying Memory Leaks
Memory leaks in Node.js typically manifest as the Heap continuously growing until an Out-Of-Memory (OOM) crash occurs. Common culprits include globally arrayed caches, detached closures, and forgotten EventEmitter listeners that indefinitely hold object references.