Memoization is an optimization technique used in JavaScript (and other programming languages) to speed up the execution of functions by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
How Does Memoization Work?
- When a function is called, its result is stored in a cache (object).
- If the same input is provided again, the cached result is returned instead of recalculating the result.
- This improves performance, especially for heavy calculations or recursive functions (e.g., Fibonacci, Factorials).
Example: Without Memoization
javascriptCopyEditfunction factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
This works but recalculates the result every time, which is inefficient for large inputs or repeated calls.
Example: With Memoization
javascriptCopyEditfunction memoizedFactorial() {
const cache = {};
return function factorial(n) {
if (n in cache) {
console.log('Fetching from cache:', n);
return cache[n];
} else {
console.log('Calculating result:', n);
if (n <= 1) return 1;
const result = n * factorial(n - 1);
cache[n] = result;
return result;
}
};
}
const factorial = memoizedFactorial();
console.log(factorial(5)); // Calculating result...
console.log(factorial(5)); // Fetching from cache
Key Points about Memoization:
Feature | Description |
---|---|
Purpose | Avoid redundant calculations by caching results. |
Performance Benefit | Useful for expensive functions (e.g., recursion). |
Data Structure Used | Usually an object ({} ) is used as a cache. |
Input as Key | Inputs act as keys in the cache to retrieve results. |
When to Use Memoization:
- Expensive Computations – Functions that take a lot of time to compute.
- Recursive Problems – Problems like Fibonacci sequence, Factorials, and Dynamic Programming.
- Repeated Calls with Same Input – When the same input is expected to be used multiple times.
Simple Memoization Utility Function
javascriptCopyEditfunction memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) {
console.log('Fetching from cache:', args);
return cache[key];
} else {
console.log('Calculating result:', args);
const result = fn(...args);
cache[key] = result;
return result;
}
};
}
// Usage example:
const add = (a, b) => a + b;
const memoizedAdd = memoize(add);
console.log(memoizedAdd(1, 2)); // Calculating result
console.log(memoizedAdd(1, 2)); // Fetching from cache
Memoization is a powerful technique for improving the efficiency of functions, especially when dealing with large datasets or complex calculations.