Garbage Collection Mechanics & Generational Hypothesis:
- Core Principle: The Generational Hypothesis states that most objects die young. Modern engines (V8) partition memory into two main generations to optimize collection efficiency:
1. Young Generation (Scavenge Collection):
- Sized small (1-64MB) for ultra-fast allocations. Divided into two semi-spaces: From-Space and To-Space using Cheney's copying algorithm.
- Process: Live objects are copied from From-Space to To-Space, leaving dead objects behind to be cleared in bulk. Spaces swap roles.
- Promotion: Objects that survive two young-generation collections are promoted to the Old Generation.
2. Old Generation (Mark-Sweep-Compact):
- For long-lived objects (closures, global variables, large data structures).
- Major GC Phases:
- Mark: Identifies all reachable objects traversing root references.
- Sweep: Reclaims memory occupied by unreachable dead objects, adding space to a free list.
- Compact: Shifts surviving objects together in memory to defragment the heap and prevent allocation failures.
3. Concurrency & Incremental Marking:
- V8 interleaves marking tasks with JavaScript execution in micro-slices to prevent long 'Stop-The-World' pauses that freeze UI frame rates.