Memoize expensive functions

suggest change

Memoization caches a function's result for a previously seen input. It is appropriate when the function is deterministic for that input and the saved computation is worth the cache's memory and lookup cost.

function memoizeByFirstArgument(fn) {
  const cache = new Map();

  return function memoized(argument) {
    if (cache.has(argument)) {
      return cache.get(argument);
    }

    const result = fn.call(this, argument);
    cache.set(argument, result);
    return result;
  };
}

const square = memoizeByFirstArgument((number) => number * number);
square(12); // Computes 144.
square(12); // Returns the cached 144.

Use Map.has() rather than testing the cached value's truthiness, because valid results such as 0, false, and undefined are falsy. Map also avoids accidental collisions with object-prototype property names.

Multiple arguments

A nested map preserves argument identity without serializing values:

function memoize(fn) {
  const root = new Map();
  const resultKey = Symbol("result");

  return function memoized(...args) {
    let node = root;

    for (const argument of args) {
      if (!node.has(argument)) node.set(argument, new Map());
      node = node.get(argument);
    }

    if (node.has(resultKey)) return node.get(resultKey);

    const result = fn.apply(this, args);
    node.set(resultKey, result);
    return result;
  };
}

Using JSON.stringify(args) as a cache key is simpler but has important limitations: property order can matter, unsupported values can collide, cyclic objects throw, and distinct objects with the same serialized content become the same key.

Memoization can retain arguments and results indefinitely. Production implementations often need an eviction policy, a size limit, or WeakMap storage for object keys. Caching rejected promises may also be undesirable, and functions that depend on time, randomness, mutable external state, or side effects generally should not be memoized without an explicit invalidation strategy.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents