22. What is memoization?

S
Soumya Jana
Mon Mar 03 2025

Memoization in JavaScript is an optimization technique used to speed up function execution by caching previously computed results. When a memoized function is called with the same arguments, it returns the cached result instead of recomputing it.

How It Works:

  1. Store function results in a cache (usually an object or Map).
  2. Before computing, check if the result exists in the cache.
  3. If found, return the cached result.
  4. If not, compute the result, store it in the cache, and return it.

Example:

javascript
function memoize(fn) { const cache = new Map(); return function (...args) { const key = JSON.stringify(args); if (cache.has(key)) { console.log("Fetching from cache:", key); return cache.get(key); } console.log("Computing result for:", key); const result = fn(...args); cache.set(key, result); return result; }; } // Example usage with a recursive Fibonacci function function fibonacci(n) { if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } const memoizedFibonacci = memoize(fibonacci); console.log(memoizedFibonacci(10)); // Computed console.log(memoizedFibonacci(10)); // Cached

Benefits:

  • Reduces redundant computations.
  • Improves performance for expensive functions.
  • Useful in recursion-heavy algorithms like Fibonacci, Factorial, and Dynamic Programming.

Would you like a more optimized example, such as a recursive Fibonacci with memoization? 🚀

Related Posts:

View All Related Posts
Sign In To Write A Comment
Copyright © 2025 codewithjana.com