-1

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.

spirytus
  • 10,726
  • 14
  • 61
  • 75
  • If you had to get the `50000+k`th value of the Fibonacci sequence (for small `k`) one million times, I think you might beg to differ. – JayC Jul 29 '14 at 00:47
  • @user2864740 could you please elaborate why fibonacci is such a bad example? What would be a better example? I'm not being a pest but genuinely want to know, thanks – spirytus Jul 29 '14 at 01:35
  • @spirytus Because it's often taught as how memoziation can make things faster .. but (unless you're doing what JayC said *many* times), it's often more efficient [just to compute it smarter](http://www.haskell.org/haskellwiki/The_Fibonacci_sequence). – user2864740 Jul 29 '14 at 01:58

1 Answers1

1

I'm not sure why the memTestHalfAsses is faster in Chrome, but that can be some optimization that goes wrong in the cache access. Other browsers doesn't show this difference.

The test doesn't really measure the difference between the implementations, only how well the cache works when the value already is in the cache. The test code will be run millions of times, and it's only the first time that the execution will differ. After that both memTest and memTestHalfAssed will both return the cached value immediately.

To see the difference between them you would need to move the creation of memTest and memTextHalfAssed from the preparation code into the test code, or empty the cache of the functions in the test code.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005