views:

156

answers:

5

hello.

In general (or from your experience), is there difference in performance between for and while loops?

What if they are doubly/triply nested?

Is vectorization (SSE) affected by loop variant in g++ or Intel compilers?

Thank you

+8  A: 

Any intelligent compiler won't really show a difference between them. A for loop is really just syntactic sugar for a certain form of while loop, anyways.

Amber
+1  A: 

it should be negligible. an optimizing compiler should make the distinction nonexistent.

sreservoir
+1  A: 

This is something easily ascertained by looking at disassembly. For most loops, they will be the same assuming you do the same work.

int i = 0;
while (i < 10)
   ++i;

is the same as

for (int i = 0; i < 10; ++i)
   ;

As for nesting, it really depends on how you configure it but same setups should yield same code.

dash-tom-bang
+1  A: 

Should be zero difference, but do check as I've seen really crappy, older versions of GCC create different code ARM/Thumb code between the two. One optimized away a compare after a subtract to set the zero flag where as the other did not. Was very lame.

Nesting again should make no difference. Not sure on SSE/Vectorization stuff, but again I'd expect there to be no difference.

Michael Dorgan
+6  A: 

Here is a nice paper on the subject.

Doug Currie
this is excellent, thank you
aaa
I think this paragraph sums it all up beautifully: "*Optimizing == important. But often: Readable code == more important.*"I tend to favour `for` loops for iteration as it is clear where your loop variable is being initialised and incremented or decremented.
Johnsyweb