4 min read
•Question 32 of 50mediumWhat is Memoization in JavaScript?
Understanding caching for function optimization.
What You'll Learn
- What memoization is
- Implementation
- Use cases
What is Memoization?
Memoization caches function results to avoid repeated calculations for the same inputs.
Basic Implementation
code.jsJavaScript
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 expensiveFunc = (n) => {
console.log('Computing...');
return n * 2;
};
const memoized = memoize(expensiveFunc);
memoized(5); // Computing... 10
memoized(5); // 10 (cached)
memoized(5); // 10 (cached)Fibonacci Example
code.jsJavaScript
// Without memoization - O(2^n)
function fib(n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
// With memoization - O(n)
const fibMemo = memoize(function(n) {
if (n <= 1) return n;
return fibMemo(n - 1) + fibMemo(n - 2);
});
console.time('fib');
fib(40); // Very slow
console.timeEnd('fib');
console.time('fibMemo');
fibMemo(40); // Fast
console.timeEnd('fibMemo');With WeakMap (for objects)
code.jsJavaScript
function memoizeWithWeakMap(fn) {
const cache = new WeakMap();
return function(obj) {
if (!cache.has(obj)) {
cache.set(obj, fn(obj));
}
return cache.get(obj);
};
}