What is the JavaScript garbage collection and V8 engine?
Answer
The V8 engine (Chrome, Node.js, Edge, Deno) uses a sophisticated generational garbage collector. Heap is divided into: Young generation (small, ~1-8 MB) — most new objects start here. Collected frequently with Scavenger (Cheney algorithm) — objects that survive two GC cycles are promoted to old generation. Old generation (large) — uses Mark-Sweep-Compact: mark reachable objects from roots, sweep unreachable ones, compact to reduce fragmentation. V8 uses incremental marking (spread GC work over multiple small pauses), concurrent marking (mark on background threads while JS runs), and parallel sweeping. This minimizes "stop-the-world" pauses. Hidden classes (Shapes): V8 creates internal "hidden classes" for objects with the same property layout — enables JIT compilation optimizations. Adding properties in different orders creates different hidden classes — avoid this for performance. Inline caches: V8 caches property lookup results for objects of the same hidden class. Deoptimization occurs when assumptions are violated (polymorphic property access). Writing predictable, consistently-shaped objects is key to V8 performance.
Previous
What are JavaScript Proxy traps in depth?
Next
What is JavaScript's type system and coercion in advanced detail?