Optimise your performance with memoization
Julio Leiva Díaz
Posted on June 20, 2023
Memoization allows us to increase the performance of a function by caching its previously computed results.
Since JavaScript objects behave like associative arrays, they are ideal for use as caches. Whenever a memoised function is called, its parameters are used to index the cache. If data is present, then it can be returned, without executing the entire function. However, if the data is not in the cache, then the function is executed and the result is added to the cache.
const fancyMemo = () => {
let cacheStore = {};
return (value) => {
if (value in cacheStore) {
console.log('Retriving from cache');
return cacheStore[value];
} else {
console.log('Calculating...');
let result = [...new Array(value).keys()]
cacheStore[value] = result
return result;
}
}
}
const newMemo = fancyMemo();
console.time('First call')
newMemo(100000) // The first time all the calculation will be done...
console.timeEnd('First call')
console.time('Second call')
newMemo(100000) // The second time the value stored in the cache will be returned
console.timeEnd('Second call')
As you can see in the example, the first execution takes
7.97607421875 ms, while the second one takes much less time to execute because it is making use of the cache.
Memorization is a programming technique widely used in the most used frameworks and libraries, so it is advisable to know it from its basic and native implementation.
I hope you found it useful.
Posted on June 20, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.