factorial recursive v. iterative

JavaScript performance comparison

Test case created by

Preparation code

<script>
var factorialRecursive = (function () {
	// 0! = 1 just 'cause
	var factorials = [ 1 ];

	return function fFactorial( n ) {
		if ( n < 0 ) {
			// negative n! not defined
			return null;
		} else if ( factorials[ n ] ) {
			return factorials[ n ];
		} else {
			factorials[ n ] = n * fFactorial( n - 1 );
			return factorials[ n ];
		}
	};
}());

var factorialIterative = (function () {
	// 0! = 1 just 'cause
	var factorials = [ 1 ];

	return function ( n ) {
		var j = factorials.length;

		if ( n < 0 ) {
			// negative n! not defined
			return null;
		} else {
			while( j <= n ) {
				factorials[ j ] = j * factorials[ j - 1 ];
				j += 1;
			}
			return factorials[ n ];
		}
	};
}());
</script>
    

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
recur
factorialRecursive(12);
pending…
iter
factorialIterative(12);
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.

0 Comments