Belajar
← All lessons

How garbage collection works

Mark what's reachable, sweep the rest

heap.js

let user = { name: "Ana" };user.profile = { avatar: "ana.png" };let cart = { items: [] }; function link() {  const a = {};  const b = { prev: a };  a.next = b;}link(); // a and b now only point at each other user = null;

gc.js

// roots: globals plus every live stack framefunction collect(roots, heap) {  const marked = new Set(roots);  const queue = [...roots];  while (queue.length) {    const obj = queue.shift();    for (const ref of refsOf(obj)) {      if (marked.has(ref)) continue;      marked.add(ref);      queue.push(ref);    }  }  for (const obj of heap) {    if (!marked.has(obj)) free(obj);  }}

Cut references yourself then run the collector

References. Press one to cut it
Why each object stays or goes

app.js

(function setup() {  const app = {}, store = {}, user = {}, feed = {}, image = {};  window.app = app;  app.store = store;  store.feed = feed;  store.user = user;  feed.cover = image;  image.owner = feed;  user.lastFeed = feed;})(); // setup() returned, so its locals are gone function compose() {  let draft = {};  draft.author = app.store.user;  // compose() is still running, so draft is on the stack}

cuts.js

// each cut runs one of these lineswindow.app = null;app.store = null;store.feed = null;store.user = null;feed.cover = null;image.owner = null;user.lastFeed = null;draft = null;draft.author = null;

Leak memory through a listener then try to collect it

When the panel closesremoveEventListenerForget itCache it
Closed panels still in memory
What holds each one

Pretend sizes: each panel holds a 2 MB array

panel.js

const cache = []; function openPanel() {  const el = document.createElement("div");  const panel = { el, data: new Float64Array(262144) }; // 2 MB  const onScroll = () => draw(panel, scrollY);  window.addEventListener("scroll", onScroll);  document.body.append(el);  cache.push(panel); // only when you cache it   return function close() {    el.remove();    // skipped when you forget    window.removeEventListener("scroll", onScroll);  };}

Topics

Next: How debounce and throttle work

Open lesson