[英]Javascript Memoization Implementation
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.事实上,时间日志显示,第一次需要更多的时间(这是我们所期望的),而之后的时间更少。
it's not correct这是不正确的
The code you shows您显示的代码
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];
};
}
is basically基本上是
function memoize(result) {
return result
}
in memoization what you cache is input/output pair and skip real function call when input match.在记忆中,您缓存的是输入/输出对,并在输入匹配时跳过真正的 function 调用。
something like:就像是:
function get(func) {
let cache = {};
return function(key) {
if (key in cache) {
return cache[key];
}
cache[key] = func(key);
return cache[key];
};
}
function expensiveCalculation(param) {
console.log('expensive calculation runs')
let counter = 0;
for (let i = 0; i < 10000; i++) {
counter += i;
}
return param*2;
}
const memo = get(expensiveCalculation)
console.log('start')
console.log('first try');
console.log(memo(10));
console.log('second try');
console.log(memo(10));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.