JavaScript, inside out · Chapter 45 of 51

Memory and performance

By the end of this chapter you can find what keeps old objects in memory, and let go of them: listeners, timers, caches and references. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Under the hood
  • 5 tasks
  • JavaScript
  • In the all labs plan

The first 2 chapters of JavaScript, inside out are free. This one comes with the all labs plan.

Why you need this

The order screen on the counter tablet gets slower every day, so Ravi has started rebooting it at 5 pm, right in the rush. Kabir watches the memory graph in the browser's dev tools climb all day: every order the tablet has ever seen is still in memory.

With what you know so far, there is no way to free an object yourself: JavaScript has no "delete this from memory". A Map that caches every order's receipt keeps every order forever. A listener added for each screen stays after the screen is gone, and a setInterval runs until the tab closes. Nothing is broken, so nothing tells you.

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    makeReceiptCache: receipts in a WeakMap keyed by the order

    Write makeReceiptCache(render). Return an object with one method, get(order). The first time get sees an order object it calls render(order), stores the receipt and returns it; every later get with that same object returns the stored receipt without calling render again.

    Store the receipts in a WeakMap, with the order object itself as the key and the receipt as the value (the check watches the WeakMap's set). Do not change the order object: no new keys on it. A different object with the same contents is a different order and is rendered again. An empty receipt, '', is cached like any other.

  2. Task 2

    memoizeLimited: remember only the most recently used few

    Write memoizeLimited(fn, max). Return a function of one argument that gives the same result as fn, but remembers results so fn is called only once per argument while that result is kept. Keep at most max results. When a new result would make it more than max, drop the least recently used one; using a remembered result counts as using it.

    With max 2, calling it with 1, 2, 1, 3, 1, 2 calls fn with 1, 2, 3 and then 2 again (3 pushed 2 out, because 1 had just been used). Falsy results, such as 0, are remembered too.

  3. Task 3 · interview question

    Interview: watchOrders, fix the listener that never goes away

    watchOrders(target, onOrder) is broken. It should call onOrder(event.detail) for every 'order' event on the target, and return a stop function that removes the listener, so that after stop() no more orders arrive. Right now stop() removes nothing, and orders keep arriving.

    Fix it. Two watchers on the same target are independent: stopping one leaves the other running.

  4. Task 4

    startPolling: poll a delivery and always clear the timer

    Write startPolling(check, ms). Call check() every ms milliseconds, the first call after ms (not straight away). As soon as check() returns 'delivered', stop: clear the interval so check is never called again and no timer is left.

    Return a stop function that stops it early, also clearing the interval, so no timer is left.

  5. Task 5

    makeLastViewed: remember a rider without keeping them alive

    Write makeLastViewed(). Return an object with two methods. remember(rider) stores a new WeakRef to the rider (made inside remember, each time it is called), replacing any earlier one. get() returns the remembered rider, or undefined when nothing has been remembered yet or the rider has been collected.

    Keep no ordinary reference to the rider anywhere, only the WeakRef: the check pretends the rider was collected and expects undefined.

What you will learn

  • Reachability: the one rule the garbage collector uses.
  • The usual leaks: listeners never removed, timers never cleared, caches that only grow.
  • WeakMap and WeakRef: holding on to an object without keeping it alive.
  • A cache with a size limit: keep the most recently used few.

More in Under the hood

Build "Memory and performance" yourself

Tapri, a chai brand going online, needs its menu, orders and kitchen in code. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of JavaScript, inside out are free. This one comes with the all labs plan.