0
0
JavascriptHow-ToBeginner · 3 min read

How to Memoize Function in JavaScript for Faster Performance

To memoize a function in JavaScript, create a wrapper that stores results of previous calls in a cache object keyed by function arguments. When the function is called again with the same arguments, return the cached result instead of recalculating it.
📐

Syntax

A memoized function uses a cache object to save results. The basic syntax wraps the original function and checks if the result for given arguments exists in the cache. If yes, it returns the cached value; if no, it computes and stores it.

  • fn: The original function to memoize.
  • cache: An object storing results keyed by arguments.
  • args: Arguments passed to the function, used as cache keys.
javascript
function memoize(fn) {
  const cache = {};
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache.hasOwnProperty(key)) {
      return cache[key];
    }
    const result = fn(...args);
    cache[key] = result;
    return result;
  };
}
💻

Example

This example memoizes a slow function that calculates Fibonacci numbers. It caches results to avoid repeated calculations, making subsequent calls faster.

javascript
function memoize(fn) {
  const cache = {};
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache.hasOwnProperty(key)) {
      return cache[key];
    }
    const result = fn(...args);
    cache[key] = result;
    return result;
  };
}

function slowFib(n) {
  if (n <= 1) return n;
  return slowFib(n - 1) + slowFib(n - 2);
}

const fastFib = memoize(slowFib);

console.log(fastFib(10));
console.log(fastFib(10));
Output
55 55
⚠️

Common Pitfalls

Common mistakes when memoizing functions include:

  • Using mutable objects as cache keys without serialization, causing incorrect cache hits.
  • Not handling functions with multiple or complex arguments properly.
  • Ignoring the possibility of cache growing indefinitely, which can cause memory issues.

Always serialize arguments (e.g., with JSON.stringify) and consider cache size limits for real applications.

javascript
function badMemoize(fn) {
  const cache = {};
  return function(arg) {
    if (cache.hasOwnProperty(arg)) { // Problem: arg might be an object or falsy value
      return cache[arg];
    }
    const result = fn(arg);
    cache[arg] = result;
    return result;
  };
}

// Correct approach uses JSON.stringify for keys
function goodMemoize(fn) {
  const cache = {};
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache.hasOwnProperty(key)) {
      return cache[key];
    }
    const result = fn(...args);
    cache[key] = result;
    return result;
  };
}
📊

Quick Reference

  • Wrap your function with a memoizer that stores results.
  • Use a cache object keyed by serialized arguments.
  • Return cached results when available.
  • Be careful with argument types and cache size.

Key Takeaways

Memoize by caching function results keyed by arguments to avoid repeated work.
Use JSON.stringify to create reliable cache keys from function arguments.
Beware of cache size growth and argument types when memoizing.
Memoization improves performance especially for expensive or recursive functions.