Factorials

JavaScript performance comparison

Revision 2 of this test case created by Joshua Holbrook

Preparation code

<script>
  var factorialR = function (n) {
      return n ? n*factorialR(n-1) : 1;
  };
 
  var factorialL = function  (n) {
    var result = 1;
    for (; n > 1; n--) {
      result *= n;
    }
    return result;
  }
 
  var factorialL2 = function  (n) {
    var result = 1;
    while (n-- > 1) {
      result *= n;
    }
    return result;
  }
</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
Recursive
var r = factorialR(20);
if (r !== 2432902008176640000) {
  throw new Error('Recursive failed hard');
}
pending…
Linear
var r = factorialL(20);
if (r !== 2432902008176640000) {
  throw new Error('Linear failed hard');
}
pending…
Linear 2
var r = factorialL2(20);
if (r !== 2432902008176640000) {
  throw new Error('Linear failed hard');
}
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