I put together simple memoization example and run few performance tests but do not understand why on Chrome memTestHalfAssed
is the fastest, even though fibonacciH
calls inside are not memoized. Tests are at http://jsperf.com/moize-test
function fibonacci(n) {
return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
}
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() {
var t=this;
return function() {
return t.memoized.apply(t,arguments);
//return t.memoized(arguments[0]);
}
}
memTest= (function fibonacciM(n) {
return n < 2 ? n : fibonacciM.memoized(n - 1) + fibonacciM.memoized(n - 2);
}).memoize();
memTestHalfAssed = (function fibonacciH(n) {
return n < 2 ? n : fibonacciH(n - 1) + fibonacciH(n - 2);
}).memoize();
EDIT:
I updated the Revision 1 tests as per Gaffa's answer and now it seems to make more sense.