Factorial cache

JavaScript performance comparison

Revision 5 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 = n;
      while (--n) {
        res = n * res;
      }
      return res;
    }
   
    function factorial4(n) {
      buf = 1;
      for (var i = n; i > 1; i--) {
        buf *= i;
      }
      return buf;
    }
   
    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
factorial(10)
pending…
Factorial With Cache
factorial2(10)
pending…
Iterative Factorial
factorial3(10)
pending…
for loop
factorial4(10)
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