Memoization vs. Direct calling

JavaScript performance comparison

Revision 2 of this test case created by Addy Osmani

Preparation code

<script>
  /*
  * memoize.js
  * by @philogb and @addyosmani
  * further optimizations by @mathias
  * Released under an MIT license.
  */

  function memoize2( fn ) {  
      return function () {  
          var args = Array.prototype.slice.call(arguments),  
              hash = "",  
              i  = args.length;  
              toString = Object.prototype.toString,
              callEm = toString.call({}),
              currentArg = null;
          while(i--){  
            currentArg = args[i];
            hash += (callEm == toString.call(currentArg)) ?  
            JSON.stringify(currentArg) : currentArg;  
            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];
  }
 
 
     var fib, fiborg, f;
      fiborg = fib = f = function (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
fib = memoize2(fiborg);
console.log(fib(25),'test1-norm');
pending…
Directly calling
console.log(fib(25));
console.log(fib(25)); //on purpose as a second call is being made. This is to simulate the cache request found in the other tests.
pending…
Memoize7
console.log(memoize7(25),'test7-norm');
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