Memoization In JS

Viraj Kamble
2 min readMay 23, 2021

--

Memoization In Js

Memoization is a form of caching where the return value of a function is cached based on its parameters. If the parameter of that function is not changed, the cached version of the function is returned.

See the example below:

Normal Addition Function

As you can see in the above example, a normal addition function is made and two parameters are passed in it and the addition of these two parameters is returned.

The above function has no problem/ error in it. But if we are passing the same parameters again, those parameters are considered as new ones and are computed again and again.

By memoization technique, we can add a check for the parameters and cache the result and return it as is if the same parameters are passed, hence saving the computation time that is required for the function to do it. See the example below:

Memoized Addition Function

As you can see in the above example the same addition function is modified to memoized function. Here now if the same parameters are passed then it will return the cached result instead of computing it again and hence saving the computation time of the machine.

If the same parameters are passed in a function that was done computing before with it, the generated result is cached and the parameters are checked if they’re passed again or not and the cached result is returned for the same parameter case.

Note:

  1. This technique is used for expensive functions only. The above example is used just for understanding the concept.
  2. Although using memoization saves time, it results in larger consumption of memory since we are storing all the computed results.

References:

Code:

--

--

Viraj Kamble
Viraj Kamble

No responses yet