Table Of Contents
Memoization is an optimization technique that is used on functions. When a memoised function is called, it caches what arguments it was passed & the output it returned. The next time it is called, it checks the cache to see if these new inputs are the same as the previous.
- If they are, instead of preforming its calculation again, it just returns the return value it has in its cache
- If they aren't, it performs its calculation & adds another record to its cache.
This means the function never performs its calculation on the same inputs twice. Reducing CPU time (at a cost of more memory). This technique is used when there is a computationally expensive function that was taking a long time to complete & impacting UX (User Experience).
Below is an example of a function that takes a number, multiples it by 2, then returns the result. It also logs everytime it performs the calculation. We are calling this function 3 times. The 3rd call has the same argument as the 1st. You can see in the console that the function is calculating each time it is called.
Let memoise the function by defining a
cache object our function will check everytime its called.
Each time its called, it will:
- do its calculation, return the value & add an entry to the
- return a value stored in the
You can see in the console, the 3rd time we called the function (with the same input as the 1st call), no calculation was logged.
Instead, the function just returned the value from the