Node.js & Libuv•Part 2: Runtime Internals, Libuv & The Event Loop (6 - 20)
V8 Garbage Collection in Node.js.
In Simple Words: V8 uses a Generational Garbage Collector divided into two main spaces:
- Scavenge (Young Generation): Two semi-spaces (From/To). Fast, frequent collection using Cheney's copying algorithm for short-lived objects.
- Mark-Sweep-Compact (Old Generation): Marks surviving long-lived objects, sweeps unmarked memory, and compacts fragmented pages to optimize pointer allocation.
bash
# Run with trace-gc flags to observe GC in real-time:
node --trace-gc --max-old-space-size=4096 server.js
# Output: [1234:0x...] [Scavenge 4.2MB -> 1.1MB] [Mark-sweep 128MB -> 45MB]