我读过
http://www.sitepoint.com/implementing-memoization-in-javascript/
自动内存
In all of the previous examples, the functions were explicitly modified to add memoization. It is also possible to implement a memoization infrastructure without modifying the functions at all. This is useful because it allows the function logic to be implemented separately from the memoization logic. This is done by creating a utility function which takes a function as input and applies memoization to it. The following memoize() function takes a function, “func”, as input. memoize() returns a new function which wraps a caching mechanism around “func”. Note that this function does not handle object arguments. In order to handle objects, a loop is required which would inspect each argument individually and stringify as needed.
function memoize(func) {
var memo = {};
var slice = Array.prototype.slice;
return function() {
var args = slice.call(arguments);
if (args in memo)
return memo[args];
else
return (memo[args] = func.apply(this, args));
}
}
用这个,我做到了
var fib = function(n)
{
if (n <= 1)
{
return 1; // as the Fib definition in Math
}
else
{
return fib(n - 2) + fib(n - 1); // as the Fib definition in Math
}
};
log(memoize(fib)(43));
log(fib(43));
但是,我确认没有效果。
出于同样的目的,我还尝试了 npm 库,
https://github.com/medikoo/memoize
和
var memoize = require('memoizee');
log(memoize(fib)(43));
log(fib(43));
结果是一样的。
我错过了什么,如何修复并使其发挥作用?
谢谢!
编辑
require('memoizee');
var fib = function(n)
{
if (n <= 1)
{
return 1; // as the Fib definition in Math
}
else
{
return fib(n - 2) + fib(n - 1); // as the Fib definition in Math
}
};
var generator = function(f)
{
return memoize(f);
};
var _fib = generator(fib);
console.log(_fib(40)); //no effect
最佳答案
memoize
调用不会改变 fib
函数,而是返回其新的、已内存的对应函数。在您的代码中,您仅调用该函数一次,下次调用原始 fib
函数。您需要创建一个内存的“包装器”,并调用它多次次:
var mFib = memoize(fib);
log(mFib(43));
log(mFib(43));
您还可以覆盖原始的 fib = memoize(fib);
,这将带来额外的好处,即递归调用(有趣的调用)也将被内存。
关于javascript - 在 JavaScript 中实现自动内存(返回闭包函数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24488862/