Skip to article content
FrontendXLesson 27 / 30

Performance and Memory

Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.

advanced · about 45 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Measure before optimizing with the Performance API.
  • Identify common memory leaks in long-lived pages.
  • Reduce layout thrash and unnecessary work.

Overview

#

Measure first

Optimization without measurement is guessing. performance.now returns a high-resolution timestamp, and PerformanceObserver reports long tasks. Record a baseline, change one thing, and measure again. A change that does not move the metric should be reverted.

snippet.js
const start = performance.now();
doWork();
console.log(performance.now() - start, 'ms');

Memory leaks

A leak is memory that is still reachable but no longer needed. Common causes are listeners that are never removed, timers that keep running, closures that capture large objects, and caches that grow without a bound. A WeakMap lets a cache entry disappear when its key is collected, and clearing timers and listeners on teardown frees their closures.

Rendering and layout

Reading a layout property such as offsetHeight after writing a style forces the browser to recompute layout, which is called layout thrash. Batch reads, then writes, then reads again. Virtualize long lists, defer non-critical work, and memoize expensive pure computations, but only after profiling shows they matter.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    What does this line print?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    const start = performance.now();
    let sum = 0;
    for (let i = 0; i < 1000; i++) sum += i;
    console.log(typeof (performance.now() - start) === 'number');
    Choose the best answer
  2. Exercise 2Explain

    Explain why a listener that is never removed can leak memory.

    starter.text
    element.addEventListener('scroll', () => bigObject.update());

    Reveal the reference answer
    reference.text
    The listener closure keeps a reference to bigObject and to element. As long as the listener is registered, the browser keeps the closure alive, and the closure keeps everything it captures reachable, so the garbage collector cannot free them even if the page no longer needs them. Removing the listener on teardown drops that reference and lets the memory be reclaimed.

    Authored expected output: the closure keeps captured objects reachable

    The answer should connect the registered listener to the reachable closure and the objects it captures.

  3. Exercise 3Implement

    Implement `benchmark(fn, iterations)` so it returns the average milliseconds per call over the given iterations.

    starter.javascript
    function benchmark(fn, iterations) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function benchmark(fn, iterations) {
      const start = performance.now();
      for (let i = 0; i < iterations; i++) fn();
      return (performance.now() - start) / iterations;
    }

    Authored expected output: the average milliseconds per call

    Timing the whole loop and dividing by the iteration count amortizes timer overhead and gives a stable per-call figure.

  4. Exercise 4Debug

    This component adds a timer on mount but never clears it, so work keeps running after unmount. Find and fix the bug.

    starter.javascript
    function mount() {
      setInterval(() => poll(), 1000);
    }
    function unmount() {
      // nothing
    }

    Reveal the reference answer
    reference.javascript
    function mount() {
      const id = setInterval(() => poll(), 1000);
      return id;
    }
    function unmount(id) {
      clearInterval(id);
    }

    Authored expected output: the interval is cleared on unmount

    setInterval returns an id that clearInterval needs. Keeping the id and clearing it on unmount stops the callback and lets its closure be collected.

  5. Exercise 5Test

    Write assertions that prove a bounded cache never exceeds its limit.

    starter.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }

    Reveal the reference answer
    reference.javascript
    class LruCache {
      constructor(limit) { this.limit = limit; this.map = new Map(); }
      set(key, value) {
        if (this.map.has(key)) this.map.delete(key);
        this.map.set(key, value);
        if (this.map.size > this.limit) this.map.delete(this.map.keys().next().value);
      }
      get(key) { return this.map.get(key); }
    }
    const cache = new LruCache(2);
    cache.set('a', 1); cache.set('b', 2); cache.set('c', 3);
    assertEqual(cache.get('a'), undefined, 'oldest entry was evicted');
    assertEqual(cache.get('c'), 3, 'newest entry is present');
    console.log('all assertions passed');

    Authored expected output: all assertions passed

    A Map preserves insertion order, so the first key is the oldest. Evicting it when size exceeds the limit bounds the cache and prevents unbounded growth.

  6. Exercise 6Interview

    How do you investigate a page that becomes slow after being open for a while?

    Reveal the reference answer
    reference.text
    I reproduce it and measure: I record a performance profile and watch memory over time to see whether it grows without bound. If memory grows, I look for listeners and timers that are never cleared, closures that capture large data, and unbounded caches. If it is CPU, I look for repeated work and layout thrash. I fix one cause, then re-measure against the baseline rather than trusting the change by eye.

    The answer should start from measurement, separate memory from CPU causes, and verify the fix against a baseline.

Common misconceptions

#
  • A faster-looking rewrite is faster without measurement.
  • Garbage collection frees objects that are still referenced by a listener.
  • Memoizing every function improves performance.

Follow-up practice

#
  • javascript-foundations-testing-javascript
  • javascript-foundations-arrays-and-iteration

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.