



Planted:
Tended:
Status: decay
Memoization is an optimization technique that is used on functions. When a memoised function is called, it caches what arguments it was passed and 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.
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 and 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.
const myFunc = (input) => {console.log('calculating...');const value = input * 2;return value;};myFunc(1);myFunc(2);myFunc(1);
Let memoise the function by defining a cache object our function will check everytime its called.
Each time its called, it will:
cache orcache.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 cache.
const cache = {};const myFunc = (input) => {if (cache[input]) {return cache[input];};console.log('calculating...');const value = input * 2;cache[input] = value;return value;};myFunc(1);myFunc(2);myFunc(1);
Have any feedback about this note or just want to comment on the state of the economy?

