Factorial cache

JavaScript performance comparison

Revision 2 of this test case created by zaus

Info

some more methods

Preparation code

Obviously caching wins.

<script>
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;
}

function factorial4(n){
        var j = n;
        while (--j) {
                n *= j;
        }
        return n;
}

function factorial5(n){
        for (var j = n-1; j > 1; j--) {
                n *= j;
        }
        return n;
}
function factorial5b(n){
        for (var j = n; j > 1; --j) {
                n *= j;
        }
        return n;
}

function factorial5c(n){
        for (var j = n; j > 1; --j) {
                n = n * j;
        }
        return n;
}


function factorial5_cache(n){
  if(! this.cache) this.cache = [1];
  if(! this.cache[n] ) {
    var n0 = n;
        for (var j = n0-1; j > 1; j--) {
                n0 *= j;
        }
    this.cache[n] = n0;
  }
        return this.cache[n];
}

var n;

</script>

<p>Do they work?</p>
<script>
// do they work?
n = 7;
document.write(
factorial(n) == factorial2(n) ? "YES" : "NO"
);
document.write(
factorial(n) == factorial3(n) ? "YES" : "NO"
);
document.write(
factorial(n) == factorial4(n) ? "YES" : "NO"
);
document.write(
factorial(n) == factorial5(n) ? "YES" : "NO"
);

</script>
<script>
Benchmark.prototype.setup = function() {
    n = Math.floor(Math.random() * 170);
   
};
</script>

Preparation code output

Obviously caching wins.

Do they work?

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(n);
pending…
Factorial With Cache
factorial2(n);
pending…
Iterative Factorial
factorial3(n);
pending…
While Factorial
factorial4(n);
pending…
For-single-line Factorial
factorial5(n);
pending…
For-single-line Factorial 2
factorial5b(n);
pending…
For-single-line Factorial with cache
factorial5_cache(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