Belajar
← Semua pelajaran

Cara kerja garbage collection

Tandai yang terjangkau, sapu sisanya

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 dan b sekarang cuma saling menunjuk user = null;

gc.js

// root: variabel global plus tiap stack frame yang masih hidupfunction 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);  }}

Putus referensinya sendiri lalu jalankan collector-nya

Referensi. Tekan salah satu untuk memutusnya
Kenapa tiap objek bertahan atau hilang

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() sudah selesai, jadi variabel lokalnya hilang function compose() {  let draft = {};  draft.author = app.store.user;  // compose() masih berjalan, jadi draft ada di stack}

cuts.js

// tiap putusan menjalankan salah satu baris iniwindow.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;

Memory leak lewat listener lalu coba bersihkan

Saat panel ditutupremoveEventListenerLupa dilepasSimpan di cache
Panel tertutup yang masih di memori
Yang menahan tiap panel

Ukurannya pura-pura: tiap panel memegang array 2 MB

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); // hanya saat kamu simpan di cache   return function close() {    el.remove();    // dilewati saat kamu lupa    window.removeEventListener("scroll", onScroll);  };}

Topik

Berikutnya: Cara kerja debounce dan throttle

Buka pelajaran