Factorial cache

JavaScript performance comparison

Revision 6 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    function factorial(n) {
      if (n < 1) return 1
      else return n * factorial(n - 1)
    }
   
    function factorial2(n) {
      factorial2.cache = factorial2.cache || [1]
      return factorial2.cache[n] || (factorial2.cache[n] = n * factorial2(n - 1))
    }
   
    function factorial3(n) {
      var res = 1;
      for (var i = 2; i <= n; ++i)
        res = res * i;
      return res;
    }
   
    var n
};
</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
Factorial
n = Math.floor(Math.random() * 170);
factorial(n)
pending…
Factorial With Cache
n = Math.floor(Math.random() * 170);
factorial2(n)
pending…
Iterative Factorial
n = Math.floor(Math.random() * 170);
factorial3(n)
pending…
precached
factorial = (function() {
  var cache = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800, 39916800, 479001600, 6227020800, 87178291200, 1307674368000, 20922789888000, 355687428096000, 6402373705728000],
    fn = function(n) {
      return cache[n] || (cache[n] = n * fn(n - 1))
    };
  return fn;
}());
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