DEV Community

Shubham_Baghel
Shubham_Baghel

Posted on

Memoization in Javascript

Memoization

A memoized function "remembers" the results corresponding to some set of specific inputs.Functions can use objects to remember the results of previous operations, making it possible to avoid unnecessary work. This optimization is called memoization. JavaScript's objects and arrays are very convenient for this.Work avoidance is the best performance optimization technique. The less work our code has to
do, the faster it executes. Along those lines, it also makes sense to avoid work repetition.
Performing the same task multiple times is a waste of execution time. Memoization is an approach to avoid work repetition by caching previous calculations for later reuse, which makes memoization a useful technique for recursive algorithms.

When to use or memoize a function

1.Recursive function with recursive values as inputs.
2.Pure function as same input and produces same output.
3.Functions its outputs can be passed to Other function for computed results on the basis of previous result.

Algorithm

Pseudocode function to calculate the factorial of n:

function factorial (n is a non-negative integer) if n is 0 then return 1 [by the convention that 0! = 1] else return factorial(n – 1) times n end if end function

Algorithm of memoized function

A memoized version of the factorial function

function factorial (n is a non-negative integer) if n is 0 then return 1 [by the convention that 0! = 1] else if n is in lookup-table then return lookup-table-value-for-n else let x = factorial(n – 1) times n store x in lookup-table in the nth slot return x end if end function

Conclusion:

Memoization is a way to lower a function's time cost in exchange for space cost; that is, memoized functions become optimized for speed in exchange for a higher use of computer memory space. The time/space "cost" of algorithms has a specific name in computing: computational complexity. All functions have a computational complexity in time (i.e. they take time to execute) and in space.

Top comments (0)