0

Possible Duplicate:
What loop is faster, while or for

I see in three.js that there is the common code feature in many languages:

for ( var i = 0, l = something.length; i < l; i++ ) {
    do some stuff over i
}

but I read that in javascript performance can be better by using:

var i = something.length;
while(i--){
    do some stuff over i
}

Does this actually improve any performance significantly? is there a reason to prefer one over the other?

Community
  • 1
  • 1
Daniel Robinson
  • 13,806
  • 18
  • 64
  • 112
  • @user1689607: No, this is a language-specific question. That question is language-neutral. – T.J. Crowder Nov 07 '12 at 23:20
  • @T.J.Crowder: Then we can pick another one from the list on the right. http://stackoverflow.com/questions/10848552/in-javascript-why-is-a-reverse-while-loop-an-order-of-magnitude-faster-than?rq=1 – I Hate Lazy Nov 07 '12 at 23:22
  • 1
    Where did you read that? http://jsperf.com/forvswhilee – David Hellsing Nov 07 '12 at 23:22
  • @user1689607: From your second linked question: *"Okay, forget about it, there is a bug in the test"* Perfectly happy to believe this is a duplicate, but if so, let's identify it properly. – T.J. Crowder Nov 07 '12 at 23:25
  • @T.J.Crowder: Many near dupes, not sure which one would count as exact, but the answer is nearly always the same... micro optimization, depends on implementation, etc... – I Hate Lazy Nov 07 '12 at 23:34

1 Answers1

3

Does this actually improve any performance significantly?

No. Not reliably cross-browser (which is to say, across JavaScript implementations).

Moreover, note that in your example, your while loop loops backward (n to 0), the for loop you quote loops forward (0 to n). Sometimes it matters.

In general, micro-optimization is rarely appropriate, and this is particularly true in the case of JavaScript, where different implementations in the wild have markedly different performance characteristics. Instead, write code to be clear and maintainable, and address specific performance issues only if they arise, and if they arise address them on your target engines.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • +1 The browser agnostic performance police rarely consider the fact that a single extra DOMReady event could account for 10 million for loops. – David Hellsing Nov 07 '12 at 23:29