DEV Community

Arhan Khan
Arhan Khan

Posted on

Memoization in JavaScript: Cache Results and Speed Things Up

Some functions are expensive — a heavy calculation, a big search, a complex filter. If you call them twice with the same input, you get the same output, so why compute it twice? Memoization remembers past results and returns the cached answer instead of recalculating.

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;
  };
}

function slowSquare(n) {
  console.log('Computing...');
  return n * n;
}

const fastSquare = memoize(slowSquare);
console.log(fastSquare(5)); // Computing... 25
console.log(fastSquare(5)); // 25 (from cache, no computing)
Enter fullscreen mode Exit fullscreen mode

Memoization only works for pure functions — same input, same output, no side effects. A function that reads the time or fetches fresh data must never be memoized, or you will serve stale answers.

Watch the cache size too. A cache that grows forever is a memory leak. In real apps, libraries limit the cache to the most recent few dozen entries, or clear it when the underlying data changes.

React developers meet memoization constantly — useMemo and React.memo are the same idea applied to components and values. Learn the plain JavaScript version first, and the framework versions will make immediate sense.

When a function is slow and called repeatedly with the same inputs, memoization is often the simplest performance win you can get: a few lines of code, and the second call is instant.

Top comments (0)