Factorial cache

JavaScript performance comparison

Test case created by Yehor Lvivski

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…

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