JavaScript Loops
JavaScript performance comparison
Info
See this discussion in a Codecademy group forum.
I've taken the test code from this comment and modified it only slightly. In particular, I changed <= to < everywhere, because <= involves two comparisons (less than OR equal), which is unnecessary. I also changed the number of repetitions to 10 thousand because JSPerf times each test hundreds of times anyway.
Scroll down to run the tests and a little further down to see charts of previous results for different browsers.
[2013-01-25] update: fixed the bug that caused wrong results. Set the iteration count to 100 thousand.
[2013-01-30] update: fixed infinitive loop bug in the while_minus
Preparation code
<script>
Benchmark.prototype.setup = function() {
var i = 0, j = 0, k = 0, max = 100000; // loop variables
var while_loop = function() {
i = 0;
while (i < max) {
i++;
}
}
var while_minus = function() {
while (max>0) {
max--;
}
}
// the loop body is intentionally empty
var for_loop = function() {
for (k = 0; k < max; k++) { }
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
While |
|
pending… |
While and break |
|
pending… |
For |
|
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 Alex J
- Revision 2: published by Alex J
- Revision 3: published
- Revision 4: published
- Revision 5: published by Raul
0 comments