为什么需要申请记忆功能?

时间:2014-07-08 20:52:11

标签: javascript memoization

我一直在玩memoization的概念,并且显然有不同的实现。我把它放在一起,似乎工作正常:

Function.prototype.memoized = function(a) {
    debugger
    if (typeof cache === "undefined") cache = [];
    if (cache[a]) {
        return cache[a];
    } else {
        cache[a] = this(a);
        return cache[a];
    }
}

Function.prototype.memoize=function() {
  t=this;
  return function() {
   // Resig seems to use this:
   return t.memoized.apply(t,arguments);
   // why not simple this:
   //return t.memoized(arguments[0]);
  }

}

myTest = (function fibonacci(n) {

    return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}).memoize();

console.log(myTest(2));

然而,我的问题是为什么在某些实现中我看到了    return t.memoized.apply(t,arguments);而不是return t.memoized(arguments[0]);内的简单proptotype.memoize?除了传递多个未使用的参数之外,我看不出任何优势。我对apply有什么好处?

修改

更新了代码,我相信这会解决主要问题,因此在窗口上缓存为全局(我在想什么?)和递归的fibonacci不会记忆调用自身。我的实施还有其他重大问题吗?

Function.prototype.memoized = function(a) {

    if (typeof this.cache === "undefined")  this.cache = [];
    if (this.cache[a]) {
        return this.cache[a];
    } else {
        this.cache[a] = this(a);
        return this.cache[a];
    }
}

Function.prototype.memoize=function() {
  t=this;
  return function() {
   //return t.memoized.apply(t,arguments);
   return t.memoized(arguments[0]);
  }

}

myTest = (function fibonacci(n) {
    //return a * 3;

    return n < 2 ? n : fibonacci.memoized(n - 1) + fibonacci.memoized(n - 2);
}).memoize();

console.log(myTest(2));

顺便说一下,这对我来说是学习经验,纯粹为了娱乐而做,这不是任务,也不是与大学有关的事情。

1 个答案:

答案 0 :(得分:2)

通常,JavaScript函数是variadic,这意味着您需要实际注意所有这些函数。一些memoize实现通过使用JSON.stringify(arguments)作为缓存键来实现此目的。


在这种情况下,它没有任何意义,因为memoized方法也只使用一个参数。

然而,您的代码中存在比这个小错误更严重的错误。 cache是一个全局变量,它应该绑定到特定的memoized函数。此外,您的fib实施在递归调用中为not memoized,实际上它是最重要的。


编辑后的版本看起来不错(全局t变量除外)。在个人方面,我会稍微缩短/简化代码:

Function.prototype.memoize=function() {
    var t = this;
    this.cache = [];
    return function(a) {
        var cache = t.cache;
        if (typeof cache[a] == "undefined")
            cache[a] = t(a);
        return cache[a];
    };
}

var fibonacci = (function (n) {
    return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}).memoize();

console.log(fibonacci(2));