Memoization in JavaScript

Memoization in JavaScript

We extensively make use of function calls in JavaScript. We may run function calls in loops for executing the function for a set of elements. Function calls are expensive and involve some overhead. This overhead becomes very much prominent when the function is to be executed over and over again for a huge number of times. But JavaScript can help us take away a little burden of this repetitive execution of functions by introducing a concept of ‘Memoization’.

Memoization in simple terms

Memoization in very simple terms is caching. If you are aware of the term caching you would know that it means saving what you have already loaded or executed in such a way that if there are any future requests with the same set of conditions, then you can directly give out the result that you previously saved. You need not carry out the execution again.

Memoization in JavaScript

With memoization of functions you can achieve caching. Say you have a function which you may need to execute a number of times with a set of parameters which would be repeating. In such a case no need to repeat the execution again and again. All you need to do is after the first execution save the result in something like a cache. This can be either an array or an object in JavaScript which you can refer to and utilize later. Then on subsequent execution you would first check the cache for the presence of any entry for the given condition or the given set of parameters. If you find it in the cache then you simply return the result without having to execute it again. If you do not find it then you execute the function and save the result for the given condition in cache for any such future request.

Fibonacci execution using memoization in JavaScript

Since now the basics are clear, let us dig into an example that explains how we can write a function which calculates fibonacci and make it more optimized using memoization.

Consider the below example of fibonacci without memoization

This is a simple way of fibonacci. If you take a look at the last few lines you would find that first we are executing the function using the parameter 5 and after that we are executing it again using 7. So when we execute it using 7 then if you see the code it goes through the entire process of executing it for 7, 6, 5, 4, 3, 2, 1. This is unnecessary.

What if we could save the execution that we had done for the parameter 5? If this was done then for parameter 7 we would only have to execute the function for 7 and 6 and use the memoized function for 5. This would save us a lot of overhead and also time.

Take a look at the memoized version of fibonacci below

This is one of the best ways of carrying out caching of function executions to save time and overhead.

Hope you had a great time reading this article. Stay tuned for more!

Comments are closed.