Skip to content

Memoization

In one line

Memoization caches the result of expensive function calls and returns the cached value on repeated inputs.

In simple words

Memoization is an optimization technique where a function caches its result for each set of arguments it has seen. On subsequent calls with the same arguments, it returns the cached value instead of recomputing. This trades memory for speed and is a form of dynamic programming (top-down).

A pure function (one whose output depends only on its inputs, with no side effects) is safe to memoize. The cache is typically a hash map keyed by the arguments. For functions with a small range of inputs that are called repeatedly, memoization can turn an exponential algorithm into a linear one.

React's useMemo and useCallback hooks memoize values and functions across renders. Python's functools.lru_cache decorator adds memoization with a least-recently-used eviction policy. The key trade-off is memory usage versus computation time — memoize when the computation is expensive and the inputs repeat.

Example

javascript
// Generic memoize wrapper
function memoize(fn) {
  const cache = new Map();
  return (...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 slowSquare = memoize(n => {
  console.log("computing", n);
  return n * n;
});
console.log(slowSquare(4)); // computing 4 → 16
console.log(slowSquare(4)); // 16 (cached, no recompute)

memoize wraps a function with a Map cache. The first call computes and caches; the second call with the same args returns the cached value.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary