Question:
Are for each loops more efficient than for loops with a 'counter'?
2010-12-11 18:35:55 UTC
int[] numbers = {123,54,2345,5,654,234,6,5434,32,64,24,4…

will this :

for(int blah : numbers) {
doSomethingWith(blah);
}

take less time to run than:

for(int i=0;idoSomethingWith(blah);
}
Three answers:
lansingstudent09101
2010-12-11 21:38:55 UTC
It depends on the language, but in general, no. If you turned compiler optimizations off, it likely would, but situations where turning compiler optimization off is a good idea are rare.



The main compiler optimization that will make the difference here is called induction variable elimination, this will merge (in most circumstances) all your loop dependent counting variables into a single simpler value, but for obvious reasons this can't merge your pointers into that count because they don't follow an arithmetic pattern.



If the object-set in the for/each or for; is an array, the compiler is going to turn it into pointer arithmetic and do direct math on it (it saves you the whole dereferencing thing, plus it turns the counter into a variable that can be used in induction variable elimination, PLUS it's really convenient for another optimization called "loop invariant code-motion" to let you move the actual assignment of the address to a temporary outside the loop.



The main difference is that a regular "For" loop probably takes slightly longer to COMPILE, rather than an actual problem at run time.
modulo_function
2010-12-12 02:58:43 UTC
Probably. Anytime there's a feature of the language that's simpler and does the same thing it's usually more efficient. Efficiency is a much over-rated quality in programming, however.
wasi
2010-12-12 03:00:07 UTC
It will take the same amount time because the terminating condition for both the for loops is the same.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...