Recursion vs For Loop vs While Loop
JavaScript performance comparison
Info
Fixing the while loop.
Preparation code
<script>
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function sum_recurse(arr, i) {
i = i || 0;
var len = arr.length;
function better_recurse(arr, i) {
if (i > len) {
return 0;
} else {
return arr[i] + better_recurse(arr, i + 1);
}
}
}
function sum_while(arr) {
var total = 0,
i = arr.length;
while (i--) {
total += arr[i];
}
return total;
}
function sum_for(arr) {
var total = 0,
len = arr.length;
for (var i = 0; i < len; i++) {
total += arr[i];
}
return total;
}
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
Recurse |
|
pending… |
While Loop |
|
pending… |
For Loop |
|
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 JB
- Revision 2: published by Jacob KEssler
- Revision 3: published
- Revision 4: published
0 comments