V8 compiles and executes JavaScript source code. While developers rarely need to manage memory manually, understanding stack vs heap allocation and how the garbage collector functions is vital to prevent memory leaks in large-scale applications.
Stack vs. Heap Memory
- Stack: Fast, organized allocation. It stores primitive values and pointers to objects on the heap. Variables are automatically allocated and deallocated as functions enter and exit the call stack.
- Heap: Large, unstructured pool of memory. It stores objects, arrays, and functions. Memory must be garbage-collected once references to these objects are lost.
Garbage Collection: Mark-and-Sweep
V8 uses the Mark-and-Sweep algorithm to find and clean up unused memory:
- Mark: Starting from a root set (global objects), the collector traverses references recursively and marks all reachable objects as "active".
- Sweep: The collector sweeps through the heap and reclaims memory from any objects that were not marked as active.