Understanding how V8 manages memory helps you write code that doesn't leak. Here's the deep internals.
V8 Memory Structure
Scavenge (Minor GC)
Fast collection for the Young Generation. Uses Cheney's algorithm with two semi-spaces.
- New objects allocate in From-space
- When From-space is full, live objects are copied to To-space
- From-space and To-space swap roles
- Objects surviving two scavenges are promoted to Old Space
Scavenge is fast (1-2ms) because most objects die young (the generational hypothesis).
Mark-Sweep-Compact (Major GC)
For the Old Generation. Three phases:
- Mark: Starting from roots (global object, stack), traverse all reachable objects
- Sweep: Free memory of unmarked objects
- Compact: Move surviving objects to eliminate fragmentation
Common Memory Leaks
Debugging Memory Issues
- Chrome DevTools Memory tab: Take heap snapshots, compare to find leaks
- Allocation Timeline: See where memory is allocated over time
- Performance Monitor: Watch JS heap size in real-time
- --max-old-space-size: Increase Node.js heap limit for large datasets