Comparison of memoization implementations

JavaScript performance comparison

Revision 29 of this test case created by william malo

Preparation code

<script>
 
  function memoize1(func) {
       "use strict";
       var cache={},
           stringifyJson = JSON.stringify,
           sliceArray = Array.prototype.slice,
u;
        return function() {
            var hash = stringifyJson(sliceArray.call(arguments));
            var foo=cache[hash];
            return foo===u?cache[hash]=func.apply(this, arguments):foo;
        };
    };

  function memoize2(func) {
       "use strict";
       var cache=new Uint32Array,
           stringifyJson = JSON.stringify,
           sliceArray = Array.prototype.slice,
u;
        return function(a) {
            var u,foo=cache[a];
            return foo===u?cache[a]=func(a):foo;
        };
    };
 
  var fib1, fib2, fiborg;
  fiborg = function f(x) {
      if(x < 2) return 1; else return f(x-1) + f(x-2);
  }

fib1=memoize1(fiborg);
fib2=memoize2(fiborg);
 
</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
1
fib1((Math.random()*40)|0);
 
pending…
2
fib2((Math.random()*40)|0);
pending…
org
fiborg((Math.random()*40)|0);
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