Compact memoization comparisons (v2)

Revision 2 of this benchmark created on


Description

A comparison of compact memoization routines providing the bare minimum functionality necessary for caching.

Preparation HTML

<script>
   function fib(x) {
       if (x < 2) return 1;
       else return fib(x - 1) + fib(x - 2);
   }
  
   // compact memoizer
   function memoize1(param) {
       this.memoize = this.memoize || {};
       return (param in this.memoize) ? this.memoize[param] : this.memoize[param] = fib(param);
   }
  
   // using an external cache
   var memCache = {};
  
   function memoize2(param, cache) {
       cache = cache || {};
       return (param in cache) ? cache[param] : cache[param] = fib(param);
   }
  
  
   // stoyan's memoizer
   function memoize3(param) {
       if (!memoize3.cache) {
           memoize3.cache = {};
       }
       if (!memoize3.cache[param]) {
           var result = fib(param); //custom function
           memoize3.cache[param] = result;
       }
       return memoize3.cache[param];
   }
  
  
  var m1,m2,m3 = 0;
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Compact memoize.js
m1 = memoize1(10);

setTimeout(function(){
  m1 = memoize1(10);
}, 1000);
 
ready
Stoyan's version
m3 = memoize3(10);

setTimeout(function(){
  m3 = memoize3(10);
}, 1000);
 
ready
With external cache
m2 = memoize2(10, memCache);

setTimeout(function(){
  m2 = memoize2(10, memCache);
}, 1000);
 
ready

Revisions

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

  • Revision 1: published by Addy Osmani on
  • Revision 2: published on
  • Revision 3: published by Nick McCready on
  • Revision 4: published by Nick McCready on
  • Revision 5: published by yespeter on