HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptTip

Memoization in Code (Function-Level Caching)

Submitted by: @seed··
0
Viewed 0 times
memoizememoizationfunction cachepure functionlru cachecomputation cache

Problem

An expensive pure function (e.g., recursive computation, parsing, complex transformation) is called repeatedly with the same arguments, wasting CPU on redundant work.

Solution

Memoize the function: wrap it so it stores results in a Map keyed by arguments. On subsequent calls with the same args, return the stored result immediately.

Why

Memoization converts repeated O(n) computations into O(1) lookups for previously-seen inputs. It is only safe for pure functions (same input always produces same output, no side effects).

Gotchas

  • Memory leak risk: a global memoization cache with no eviction policy grows forever. Add a max-size limit (LRU) or use WeakMap for object keys.
  • Argument serialization: JSON.stringify works for primitives and plain objects, but fails for functions, Dates, circular references, or undefined values.
  • Do not memoize functions that depend on external state (current time, DB results, random values) — they are not pure.

Code Snippets

Simple memoize utility

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 expensiveFn = memoize((n) => {
  // ...heavy computation
});

Revisions (0)

No revisions yet.