CodeMasteryLab
Section 13

Performance Optimization & Memory Management

Memoization, lazy loading, debounce/throttle, memory leaks, garbage collection, and writing performant JavaScript.

Performance Optimization & Memory Management

Performance questions are common in senior-level interviews, especially at product companies.

Memoization

function memoize(fn) {
  const cache = new Map();
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn.apply(this, args);
    cache.set(key, result);
    return result;
  };
}

const fib = memoize(function(n) {
  if (n <= 1) return n;
  return fib(n - 1) + fib(n - 2);
});

Memory Leaks

Common causes:

  1. Forgotten timers/intervals
  2. Unreleased event listeners
  3. Closures holding large data
  4. Detached DOM nodes still referenced
  5. Accidental global variables (without var/let/const)
// Memory leak: interval runs forever
const id = setInterval(() => { /* work */ }, 1000);
// Fix:
clearInterval(id);

// Memory leak: event listener never removed
btn.addEventListener('click', handler);
// Fix:
btn.removeEventListener('click', handler);

WeakMap & WeakSet

WeakMap/WeakSet hold weak references — their keys/values can be garbage collected if no other reference exists. Ideal for caching without preventing GC.