I've been debating this topic with my mates at work. I would like to know from you guys, if this is, actually, the right way of implementing the memoization.
function memoize(result) {
let cache = {};
return function() {
if (cache[result]) {
// returns cached result / no calculation
return cache[result];
}
// calculating...
cache[result] = result;
return cache[result];
};
}
function expensiveCalculation() {
let counter = 0;
for (let i = 0; i < 1000000; i++) {
counter += i;
}
return counter;
}
console.time("FirstCalculation");
const memoizedExpensiveCalculation = memoize(expensiveCalculation());
console.timeEnd("FirstCalculation");
console.time("1_Memoized");
memoizedExpensiveCalculation();
console.timeEnd("1_Memoized");
console.time("2_Memoized");
memoizedExpensiveCalculation();
console.timeEnd("2_Memoized");
console.time("3_Memoized");
memoizedExpensiveCalculation();
console.timeEnd("3_Memoized");
The time logs reveals, in fact, the first time takes much more time (which we would expect) and less time afterwards.