Memoization with custom function properties (v2)

Revision 2 of this benchmark created by Addy Osmani on


Preparation HTML

<script>
  //by @philogb 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);
        };
    }
  
  
  //unscriptables version of stoyans memoizer
  function memoize7(param){
      if (!memoize7.cache) {
          memoize7.cache = {};
      }
      if (!memoize7.cache[param]) {
                
          console.log(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

Ready to run.

Testing in
TestOps/sec
philogb and addy's version
fib = memoize2(fiborg);
console.log(fib(20),'test1-norm');
ready
stoyans
console.log(memoize7(20),'test7-norm');
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 2: published by Addy Osmani on
  • Revision 4: published on