What is memoization and how to cache function results in Javascript
Javascript memoization is an optimizing technique to reduce time consuming calculations. It's a type of caching which store previous results in the memory.
In this post, we will learn about Javascript memoization and how to write a memoize function in Javascript.
What is memoization in JavaScript?
Memoization is an optimization technique used to speed up computer programs. It is used to reduce time-consuming calculations by storing the results of the previous function in a cache and returning the cached values when the same input occurs again.
Let's understand it with an example.
Suppose, we have a function that adds two numbers.
const add=(a,b)=>{ return a + b }
Now, whenever we run this function it consumes some time to do that calculation. We can just use the console.time() and console.timeEnd() to see the time.
console.time() console.log(add(2,2)) console.timeEnd()
Output:
4 default: 4.878ms
It took approximately 4.878ms to do the calculation.
Now suppose we have to do the same calculation over and over again with the same argument.
console.log(add(2,2)) console.log(add(2,2)) console.log(add(2,2))
Here, we are invoking the same add() function with the same arguments 3 times, which means each time it will take 4.8ms (approx) time to calculate the same arguments.
This is time-consuming as we already know the results of the add function, which is 4 when the function is executed the first time.
So, rather than computing the addition 2 more times, we can just write a memoize function to store the results and use it when the same function is invoked the second time.
Write a memoization function in Javascript
This function will identify the function with its arguments. If the previous result of the function is stored in the cache object, then it will just return the results without executing the function again.
const memoize=(fn)=>{ const cache = {} return function(...args){ uniKey = fn.name+args[0] if(uniKey in cache){ console.log('From the cache') return cache[uniKey] }else{ let result = fn(...args) cache[uniKey] = result; return result } } }
Here, we have a function called memoize, which takes in a function as an argument and returns another function that takes the arguments (...args).
Next, we have a cache object, which will store the values from the functions with a unique key (uniKey).
Here, we have concat the function name (fn.name) and the first argument of the function (args[0]) as a unique key just for the example.
uniKey = fn.name+args[0]
Next, we have an if statement to check if the result of the function is in the cache object or not. If the unique key related to the function is found in the cache, it will return the result without invoking the function.
If not, then the add function passed to the memoize function will get executed inside the else block and the result will be stored with a unique key inside the cache object like this.
cache[uniKey] = result
Because of closure the returned function can access the function that is passed as an argument.
Now, let's see an example, with memoize function implemented on function with same arguments.
const add=(a,b)=>{ return a + b } const memoize=(fn)=>{ const cache = {} return function(...args){ uniKey = fn.name+args[0] if(uniKey in cache){ console.log('From the cache') return cache[uniKey] }else{ let result = fn(...args) cache[uniKey] = result; return result } } } const memoizeAdd = memoize(add) console.time() console.log(memoizeAdd(2,2)) console.timeEnd() console.time() console.log(memoizeAdd(2,2)) console.timeEnd()
Output:
4 default: 6.354ms From the cache 4 default: 0.213ms
As you can see, the first time the function got invoked and it took 6.354ms to return the results.
And the next time, it only took 0.213ms because it returned the result from the cache without executing the add function again inside memoize function.
Conclusion: Here, we have learned what is Javascript memorization and how to use memoize to cache function results and speed up the program.
Other Articles You'll Also Like:
Javascript nullish coalescing (double question mark) operator
Related Posts
Press Shift + Enter for new Line in Textarea
Override default textarea behavior on Enter key press without Shift, prevent new lines, and take custom actions like submitting forms instead. Still allow Shift+Enter newlines.
in vs hasOwnProperty(): Differences in Inherited Properties
The article explains the differences between JavaScript's 'in' operator and 'hasOwnProperty()' method. And also learn the use cases of both in JS.
How to Fix "ReferenceError: document is not defined" in JavaScript
The "ReferenceError: document is not defined" is a common error in JavaScript that occurs when trying to access the `document` object in a non-browser environment like Node.js.
How to Fix the "Cannot Read Property of Undefined" Error in JavaScript
The "Cannot read property of undefined" error occurs when you try to access a property or method of a variable that is undefined in JavaScript.
