Compact memoization comparisons (v5)

Revision 5 of this benchmark created by yespeter 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];
   }
  
  function mem (param) {
    this.cache = this.cache || {}
    return this.cache[param] || (this.cache[param] = fib(param))
  }

  function memOne (param) {
    return (this.cache = this.cache || {}) &&
      this.cache[param] || (this.cache[param] = fib(param))
  }  
  var m1,m2,m3,m4,m5 = 0;
</script>

Test runner

Ready to run.

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

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

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

setTimeout(function(){
  m2 = memoize2(25, memCache);
}, 1000);
 
ready
small mem
m4 = mem(25);

setTimeout(function(){
  m4 = mem(25);
}, 1000);
 
ready
oneline mem
m5 = memOne(25);

setTimeout(function(){
  m5 = memOne(25);
}, 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