Possible Duplicate:
Is it faster to count down than it is to count up?
For example,
for (int i = 0; i < max; i++)
{
...
}
and
for (int i = max-1; i >= 0; i--)
{
...
}
These two loops are essentially the same, and assuming that the loop doesn’t contain any array operation. However, for the first case, every iteration will require loading max into a register in the processor and then compare between i and max.. on the other hand, the latter case doesn’t require loading 0 into a register for that 0 is already there in a register, so that there is only a comparison for the latter loop. Please correct me if I am wrong, and elaborate if I am right.
Thanks.
The code represented by the ellipsis will almost certainly relegate any actual performance difference to mere noise. However, you’re not correct in all of your assumptions.
Maybe, but probably not. This depends on your code, but any sane optimizing compiler will be able to detect if the counter is changing between iterations.
I’m not sure where you got some of your ideas, but they are a bit misguided and don’t take into account how an optimizing compiler works. Look at your disassembly and see what the real difference is yourself. Oh what the hell, I’ll do it (it’s fun anyway):
The program is:
The generated assembly (VS2010 release, comments my own) is:
And for the more idiomatic version…
So yes, the first version uses a
jnsinstruction (jump if not signed), so the comparison is simplified a bit (comparing to 0). It also contains a few more instructions, but no comparison.However, notice that the comparison made in version two is also static. It knows that
maxdoesn’t change throughout the loop, so it can optimize that bit accordingly.But I would reiterate strongly that this is not likely to ever produce an appreciable performance benefit. Even the high performance timer on my Windows PC couldn’t give me a good statistical difference between the two because the call to
couttakes soooo much longer than the loop instructions.