DEV Community

Julio Leiva Díaz
Julio Leiva Díaz

Posted on

2

Optimise your performance with memoization

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')
Enter fullscreen mode Exit fullscreen mode

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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay