Memoization vs. Direct calling

JavaScript performance comparison

Test case created by Addy Osmani

Preparation code

<script>
   //by @philogbs and @addyosmani
    function memoize2(fn) {
          return function () {
              var args = Array.prototype.slice.call(arguments),
                  hash = "",
                  i  = args.length;
              while(i--){
                hash += (Object.prototype.toString.call({}) == Object.prototype.toString.call(args[i])) ? JSON.stringify(args[i]) : args[i];
                fn.memoize = fn.memoize || {};
            }
              return (hash in fn.memoize) ? fn.memoize[hash] : fn.memoize[hash] = fn.apply(this, args);
          };
      }
   
  //stoyans version
  function memoize7(param){
      if (!memoize7.cache) {
          memoize7.cache = {};
      }
      if (!memoize7.cache[param]) {
          var result = fib(param);
          memoize7.cache[param] = result;
      }
      return memoize7.cache[param];
  }
 
   function fib(x) {
          if(x < 2) return 1; else return fib(x-1) + fib(x-2);
      }
   
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Memoize2
var fibTest2 = memoize2(fib);
console.log(fibTest2(25));

//cached
setTimeout(function(){
        fibTest2(25);
}, 1000);
pending…
Directly calling
console.log(fib(25));

//obviously this part will not be cached,
//requiring a recalculation.
setTimeout(function(){
        fib(25);
}, 1000);
pending…
Memoize7
console.log(memoize7(25));

setTimeout(function(){
  memoize7(25);
}, 1000);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment