What is memoization and when should you use it?

MediumTechnical
MetaSoftware Engineer
189

Explain the concept of memoization. Implement a memoize function and discuss when memoization is beneficial vs harmful.

1 Answer

167
Top Answer

Memoization caches function results based on arguments to avoid redundant calculations.

Implementation

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

// Usage
const expensiveFn = memoize((n) => {
  console.log('Computing...');
  return n * 2;
});

expensiveFn(5); // Computing... 10
expensiveFn(5); // 10 (cached)

When to Use:

✅ Pure functions with expensive calculations ✅ Recursive algorithms (Fibonacci, factorial) ✅ Functions called repeatedly with same args

When NOT to Use:

❌ Functions with side effects ❌ Functions with many unique inputs (cache grows forever) ❌ Simple calculations (overhead > benefit)

OptimizationPro

Share Your Answer

Help others by sharing your knowledge and experience with this question.

Coming soon...

Related Questions

View all

More from Meta

View all