docs/heap/compaction.md
Compaction is a phase of the Major Garbage Collector (Mark-Sweep-Compact) used to resolve memory fragmentation in the Old Generation and other spaces.
Over time, as objects are allocated and freed, the heap can become fragmented—full of small free spaces that are too small to satisfy new allocation requests. Compaction solves this by moving live objects closer together, creating large contiguous free spaces.
V8 does not compact the entire heap at once, as that would cause unacceptably long pause times. Instead, it identifies specific pages as "evacuation candidates" in CollectEvacuationCandidates:
max_evacuated_bytes). It sorts candidate pages by the amount of live bytes in ascending order (i.e., pages with the most free space first). It then selects the candidates that fit within the limit, maximizing reclaimed space per byte moved.ComputeEvacuationHeuristics determines the target fragmentation and max evacuated bytes based on the mode (ReduceMemory, OptimizeForMemoryUsage, or regular latency-critical mode). In regular mode, it may use trace-based compaction speed to adaptively set the threshold.OLD_SPACE, TRUSTED_SPACE, and potentially CODE_SPACE and SHARED_SPACE (with specific conditions, e.g., not compacting shared space when CSS is enabled in certain modes).The actual moving of objects happens in parallel to utilize multiple cores:
When an object is moved to a new location:
After all objects have been moved, V8 must update all references to point to the new locations in UpdatePointersAfterEvacuation:
OLD_TO_NEW: Pointers from old to new generation.OLD_TO_SHARED: Pointers from non-shared to shared space.OLD_TO_OLD: Pointers between old generation pages, specifically recorded when the target points to an evacuation candidate.TRUSTED_TO_CODE: Pointers from trusted space to code space.TRUSTED_TO_TRUSTED: Pointers within trusted space.TRUSTED_TO_SHARED_TRUSTED: Pointers from trusted space to shared trusted space.StartMarking.src/heap/mark-compact.cc: Contains the implementation of the compaction logic, including candidate selection, evacuation, and pointer updating.