According to this JSPerf the While ! Undefined style array loop is ~10x faster in all browsers. What are the disadvantages of this style of loop?
4 Answers
It is actually a bug in the test case, the iterator is not being reset to zero for each test run (i.e., only the first test run rolls the full loop, next runs have the iterator already past the end of the array, thus roll zero times). See corrected test suite for the true benchmark.
(Note: I haven't inspected all test cases, others might be flawed as well)
3 Comments
As you can see, we're talking about 10x faster/slower on a scale of millions of operations per second, which is not significant enough to worry about.
A possible disadvantage of that style is readability to other developers, which is more important than the "performance boost".
Judge yourself, what's more readable?
// Chrome 21: 5M operations per second
var a;
while ((a = arr[i++]) !== undefined) {
someFn(a);
}
// Chrome 21: 324k operations per second
for (var i = 0; i < arr.length; i++) {
someFn(arr[i]);
}
2 Comments
The major disadvantage I can see is that you can't break out of the loop! You'll hit an unresponsive UI in no time with that.
1 Comment
disadvantages: 1. if a[i] has been used it is no longer undefined. Thus you may do more than anticipated. 2. readability, it is difficult to know the end point (unless you put some comments ;) nothing else.
the new revision still doesn't differ that much, but if it's speed you need then comment well and test well.
If your function "someFn(a);" has a timer of more than in these tests then i'd recommend testing your own loop if it is that important.
If not always stick to tidy coding.
undefined.