Memoization is a technique used to speed up function execution by storing (caching) the results of expensive function calls.
When the function is called again with the same input, instead of recalculating, the result is returned from cache.
🧠 Why Use Memoization?
✔ Improves performance
✔ Avoids repeated expensive calculations
✔ Common in recursion (Fibonacci), API responses, heavy computations
✔ Used in React (useMemo, useCallback)
🚀 Simple Memoization Example
Function to memoize: Fibonacci (expensive calculation)
Without memoization:
function slowFib(n) {
if (n < 2) return n;
return slowFib(n - 1) + slowFib(n - 2);
}
Calling slowFib(40) is extremely slow.
✅ Memoized Version
function memoize(fn) {
const cache = {};
return function (...args) {
const key = JSON.stringify(args);
if (cache[key]) {
console.log("Returning from cache:", key);
return cache[key];
}
const result = fn.apply(this, args);
cache[key] = result;
return result;
};
}
🧪 Use the memoized function
const fastFib = memoize(function fib(n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
});
console.log(fastFib(10)); // calculated first time
console.log(fastFib(10)); // returned from cache
🎯 Output (for second call):
Returning from cache: [10]
55
💡 How It Works
- We wrap the function in
memoize() - Cache stores input → output mapping
- When the same input comes again → return cached value
- Avoids recomputation
✔ Real Use Cases in Projects
- Expensive calculations (Fibonacci, factorial)
- Caching API responses
- Form validation performance
- Auto-complete search results
- React performance optimization (
useMemo)