What is memoization?
Memoization is a technique that makes your function calls faster in exchange of memory space. Although it is generic for all programing languages, I'm going to use JavaScript to implement a simple memoization function.
Why to use it?
As our application grows, there may be some cases where hard computational algorithms might happen to be slowing down your application. You may want to store those computations' results and use them over and over again to improve your application's performance and that's where memoization comes in...
Memoization technique gives you the ability of caching results in function scope and lets you use it from inner functions. This caching mechanism provides you better performance especially in terms of expensive function calls.
Let's say you have a simple factorial function and you don't want to calculate factorial of any given number after it has already been calculated.
By returning a function and storing factorial result in its closure, we can create a memory cache.
As shown above, we created a memoizedFactorial function and store every calculated factorial in the cache object. This way we create closure for returning function and it has access to this cache object therefore second function call with same parameter will not call factorial function.
Conclusion
We prevent our application from calling function over and over again in the exchange of memory space because closured data is stored on heap memory.
Also you can read;
Top comments (0)