docs/heap/garbage-collection.md
V8 uses a sophisticated garbage collection (GC) system to automatically manage memory. It is a generational collector, meaning it divides the heap into different generations based on object lifetime.
The GC is based on the generational hypothesis: most objects die young. By dividing the heap into young and old generations, V8 can optimize GC pauses by collecting the young generation more frequently and quickly.
The Young Generation is where newly allocated objects are placed. It is typically small (a few megabytes to tens of megabytes) and is designed to be collected quickly.
The default collector for the young generation is the Scavenger. It uses a semi-space design:
This is a copying collector, which compacts memory as it goes, leaving no fragmentation in the young generation.
Minor Mark-Sweep is an alternative young generation collector in V8, enabled with the --minor-ms flag. Unlike the Scavenger, which is a copying collector, Minor MS uses a mark-sweep approach.
OLD_TO_NEW). It supports concurrent and parallel marking.src/heap/minor-mark-sweep.ccObjects that survive a certain number of Scavenge cycles in the young generation are promoted (tenured) to the Old Generation. This space is much larger and contains long-lived objects.
The Old Generation is collected by the Mark-Sweep-Compact collector. This is a much more involved process:
To support generational GC and incremental marking without scanning the entire heap, V8 uses Write Barriers. A write barrier is code emitted for heap stores like host.field = value to inform the GC about changes to the object graph.
The write barrier serves three main purposes (as detailed in src/heap/WRITE_BARRIER.md):
OLD_TO_NEW). This allows the Scavenger to find live young objects without scanning the whole old generation. This barrier is always enabled.Write barriers add overhead, so V8 eliminates them when safe:
To achieve low latency, V8 heavily utilizes background threads: