Memoization
Memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
1. The Concept
In JavaScript, functions are first-class objects, and we can attach properties to them or use closures to maintain state. Memoization leverages this to create a cache (usually an object or Map) where keys are the arguments passed to the function, and values are the computed results.
2. Simple Example
Imagine a function that takes a long time to run.
function slowSquare(n) {
// Simulate slow operation
for (let i = 0; i < 1000000000; i++) {}
return n * n;
}
// console.log(slowSquare(5)); // Takes a while
Now, let's memoize it using a closure.
const memoizedSquare = (function() {
const cache = {}; // Closure to hold the cache
return function(n) {
if (n in cache) {
console.log("Fetching from cache");
return cache[n];
} else {
console.log("Calculating result");
const result = slowSquare(n);
cache[n] = result;
return result;
}
};
})();
console.log(memoizedSquare(5)); // Calculating result
console.log(memoizedSquare(5)); // Fetching from cache (Instant)
3. Generic Memoization Function
You can create a helper function to memoize any function.
function memoize(fn) {
const cache = {};
return function(...args) {
// Create a unique key for the arguments
const key = JSON.stringify(args);
if (cache[key]) {
return cache[key];
}
const result = fn.apply(this, args);
cache[key] = result;
return result;
};
}
const fastSquare = memoize(slowSquare);
4. Trade-offs
- Pros: Significantly faster execution for expensive functions with repeated inputs.
- Cons: Uses more memory to store the cache. If the input space is huge and rarely repeats, memoization might just waste memory without providing speed benefits.
programming/javascript/vanilla/javascript programming/javascript/vanilla/closures