Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which loop has better performance? Increment or decrement? [duplicate]

Tags:

performance

c

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 ?*/
      }
like image 847
Rasmi Ranjan Nayak Avatar asked Jan 23 '12 08:01

Rasmi Ranjan Nayak


People also ask

Which is faster increment or decrement?

Increment is always faster than decrement.

Which operation is faster i ++ or ++ i?

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.

Which one is faster i ++ or i 1 explain?

As i++ does automatic typecasting and uses a compiler instruction which internally uses iadd instruction, i=i+1 is faster than i++.

Why prefix increment is faster?

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.


2 Answers

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.

like image 154
PhoenixS Avatar answered Oct 16 '22 12:10

PhoenixS


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)

like image 42
Veger Avatar answered Oct 16 '22 11:10

Veger