Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop instead of while loop

Tags:

jquery

Reading through the jQuery source I stumbled upon the following piece of code (available here):

for (; i < length;) {     if (callback.apply(object[i++], args) === false) {         break;     } } 

Why is a for loop used here instead of a while loop?

like image 940
Randomblue Avatar asked Aug 24 '11 00:08

Randomblue


People also ask

WHY IS for loop better than while loop?

For loops (at least considering C99) are superior to while loops because they limit the scope of the incremented variable(s). Do while loops are useful when the condition is dependant on some inputs. They are the most seldom used of the three loop types.

What is the difference between a for loop and a while loop?

The major difference between for loop and while loop is that for loop is used when the number of iterations is known whereas, in the while loop, execution is done until the statement in the program is proved wrong.

Which is more powerful for loop or while loop?

The main reason that While is much slower is because the while loop checks the condition after each iteration, so if you are going to write this code, just use a for loop instead.


1 Answers

I vote for someone having an affinity for bad coding style. That's the only explanation I can see for both the for loop and the i++ being placed inside of an array subscript. I think this would be better:

while (i < length && callback.apply(object[i], args)) {     i++; } 

Or if you happen to feel that the === operator in the original example has value, then:

while (i < length && callback.apply(object[i], args) !== false) {     i++; } 

Another possible reason for doing this may have been as a performance optimization. Although this quick benchmark that I put together seems to disprove that theory. On Windows the while loop above is 20% faster than the original for loop in Chrome, in IE and Firefox both loops perform the same. On OS X the for loop has a 10% advantage in Firefox, there is no difference between the two in Chrome, and Safari prefers the while loop by 6%.

So from a performance standpoint it's a wash. If anything then judging by market share you would probably want to optimize for Chrome on Windows before optimizing for Firefox on Mac, in which case the while loop would be preferred.

Which says to me that it's unlikely that performance optimization played a factor with this code. And I return to my original theory that it's just an example of poor coding style making it past the code-review process.

like image 191
aroth Avatar answered Sep 28 '22 23:09

aroth