Factorial cache
JavaScript performance comparison
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.
| Test | Ops/sec | |
|---|---|---|
Factorial |
|
pending… |
Factorial With Cache |
|
pending… |
Iterative Factorial |
|
pending… |
While Factorial |
|
pending… |
For-single-line Factorial |
|
pending… |
For-single-line Factorial 2 |
|
pending… |
For-single-line Factorial with cache |
|
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:
- Revision 1: published by Yehor Lvivski
- Revision 2: published by zaus
- Revision 3: published
- Revision 4: published by Inskandar Hamadrias
0 comments