Memoization

Memoization caches the result of a function based on its inputs. It is most useful for deterministic or pure computations where repeated inputs are common and the cost of computing the result is significant.

Memoization has a tradeoff: it exchanges memory for computation. An unbounded memoization cache can itself become a memory problem.

Simple 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(...args);
    cache.set(key, result);
    return result;
  };
}

const square = memoize(n => n * n);
console.log(square(10));
console.log(square(10));
💡 The second call with the same serialized arguments retrieves the cached result instead of recomputing it.
Key Takeaways
  • Memoization trades memory for computation.
  • It works best for deterministic computations.
  • Cache growth and key design must be considered.
Knowledge Check

What does memoization primarily trade for faster repeated calculations?