Compact memoization comparisons

JavaScript performance comparison

Test case created by Addy Osmani

Info

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

Preparation code

<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

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Compact memoize.js
m1 = memoize1(25);

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

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

setTimeout(function(){
  m2 = memoize2(25, memCache);
}, 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