
Memoization is a powerful optimization technique used to speed up functions by caching the results of expensive computations. When a memoized function is called with the same inputs more than once, it returns the cached result instead of re-computing it, saving processing time.
The Problem: An Expensive Function
A classic example is a recursive function to calculate Fibonacci numbers. This implementation is inefficient because it re-computes the same values many times.
function slowFib(n) {
if (n <= 1) return n;
return slowFib(n - 1) + slowFib(n - 2);
}
// slowFib(40) would take a very long time to compute.
The Solution: Memoization
We can create a higher-order function that takes a function and returns a memoized version of it.
function memoize(fn) {
const cache = {}; // Our cache
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) {
console.log('Fetching from cache...');
return cache[key];
}
console.log('Calculating result...');
const result = fn(...args);
cache[key] = result;
return result;
};
}
const fastFib = memoize(slowFib);
console.log(fastFib(10)); // Calculates and caches
console.log(fastFib(10)); // Fetches from cache
Memoization is a trade-off: it uses more memory to store the cache but significantly reduces computation time for functions that are called repeatedly with the same arguments.
Comments
Post a Comment