Module 44 // Core JavaScript

Memory Model & Garbage Collection

Module Objective

Heap vs stack, reachability, GC strategies, memory leaks

Mental Model Realtime Simulation

INTERACTIVE_CANVAS
Editor_Pane
Loading...
Console_Output
Waiting for output...

Practical Code Examples

// Example 1
// 1. Simple Memory Leak
function leak() {
  const bigData = new Array(1000000).fill("X");
  
  return function() {
    // Closure keeps bigData alive forever!
    console.log(bigData.length);
  };
}

const leakyFunc = leak();
💡 Closures are the most common cause of memory leaks. Even if you don't use `bigData`, the inner function keeps a reference to it in the Heap.
// Example 2
// 2. Disconnected DOM Leak
let element = document.getElementById('button');

function cleanup() {
  document.body.removeChild(element);
  // 'element' variable still points to the DOM node!
  // GC cannot reclaim it until element = null;
}
💡 Removing a node from the DOM isn't enough. If a JS variable still points to it, the engine keeps the entire DOM subtree in the Heap.
// Example 3
// 3. Generational GC (Orinoco)
// Modern engines use "Generations"
// - Young Generation (new objects, fast GC)
// - Old Generation (survivors, heavy GC)
💡 V8 uses a Generational Garbage Collector. Most objects die young. If an object survives two GC cycles, it's moved to the 'Old Space' which is scanned less frequently.

Engine & Memory Architecture

The Garbage Collector

1. Reachability:

  • The GC starts from "Roots" (Global object, current stack variables).
  • It "walks" the graph of pointers in RAM. Any object not reached is marked for deletion.

2. Scavenger (Young Gen):

  • Uses a "Copying" algorithm. It splits memory into two semi-spaces and copies live objects to the new space while wiping the old one. This is extremely fast.

3. Major GC (Full Mark-Compact):

  • Scans the entire Heap.
  • It moves objects together to eliminate "fragmentation" (holes in memory), ensuring contiguous space for the CPU to access.