Possible Duplicate:
Is it faster to count down than it is to count up?
which loop has better performance? I have learnt from some where that second is better. But want to know reason why.
for(int i=0;i<=10;i++)
{
/*This is better ?*/
}
for(int i=10;i>=0;i--)
{
/*This is better ?*/
}
Increment is always faster than decrement.
Though we can say that the ++i is slightly faster than i++. The i++ takes local copy of the value of i before incrementing, while ++i never does. Sometimes some compiler optimizes the code if possible.
As i++ does automatic typecasting and uses a compiler instruction which internally uses iadd instruction, i=i+1 is faster than i++.
Pre-increment is faster than post-increment because post increment keeps a copy of previous (existing) value and adds 1 in the existing value while pre-increment is simply adds 1 without keeping the existing value.
The second "may" be better, because it's easier to compare i
with 0 than to compare i
with 10 but I think you can use any one of these, because compiler will optimize them.
I do not think there is much difference between the performance of both loops.
I suppose, it becomes a different situation when the loops look like this.
for(int i = 0; i < getMaximum(); i++)
{
}
for(int i = getMaximum() - 1; i >= 0; i--)
{
}
As the getMaximum()
function is called once or multiple times (assuming it is not an inline function)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With