如果你在 Python 中使用记忆斐波那契函数,你会发现它变得更快:
import time
beg = time.clock()
def memoize(f):
cache = {}
def decorated_function(*args):
if args in cache:
return cache[args]
else:
cache[args] = f(*args)
return cache[args]
return decorated_function
@memoize
def fib(n):
if n <=2:
return 1
return fib(n-2) + fib(n-1)
var = fib(35)
end = time.clock()
print(var)
print(end - beg)
你可以在 javascript 中做同样的事情:
function memoize( fn ) {
return function () {
var args = Array.prototype.slice.call(arguments),
hash = "",
i = args.length;
currentArg = null;
while (i--) {
currentArg = args[i];
hash += (currentArg === Object(currentArg)) ?
JSON.stringify(currentArg) : currentArg;
fn.memoize || (fn.memoize = {});
}
return (hash in fn.memoize) ? fn.memoize[hash] :
fn.memoize[hash] = fn.apply(this, args);
};
}
var beg = new Date().getTime();
function fib(n)
{
if (n <= 2)
return 1;
return fib(n-2) + fib(n-1);
}
var f = memoize(fib)(35);
var end = new Date().getTime();
console.log(f);
console.log(end - beg);
看起来 javascript 方面没有性能改进,这往往表明这里已经内置了某种 memoization 机制。
学分:http : //ujihisa.blogspot.fr/2010/11/memoized-recursive-fibonacci-in-python.html,http: //addyosmani.com/blog/faster-javascript-memoization/