DEV Community

Ravina Deogadkar
Ravina Deogadkar

Posted on

Javascript: Memoization

Memoization is a technique used to save execution time by caching results of frequently used function.

Consider we have a function defined for let's say calculating area of square. Within duration of program execution function needs to be called 'n' number of times. Each time function gets called area of square is computed based on arguments passed and result is returned. It takes lot of execution time to compute area each time and return output. Here, we can make use of Memoization technique to cache result and later use the cache result instead of computing each time.

Take a look at below example.

Alt Text

Here loop runs 100 times which causes function to be called 100 times and each time area is calculated.

Now look at below example.

Alt Text

Here loop runs 100 times which causes function to be called 100 times and only once area will be computed for rest 99 times saved value will be returned.

If we look first example takes longer time than the second example. Consider multiple lines of complex computation functionality, in that case obviously Memoization will save lots of execution time.

Happy Coding!

Discussion (0)