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:
Algorithm of memoized function
A memoized version of the factorial 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)