Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

i++ or i-- in a for loop? [closed]

Tags:

java

c++

c

While writing a for loop where both start and end conditions are known, which way is better? Let's say I have to iterate a loop for addition of an array elements of size 5. In this case which one of the following would be more efficient as far as execution time is concerned? Which one will give better performance?

for (i = 0; i < 5; i++)
{
    /* logic */
}

OR

for (i = 4; i >= 0; i--)
{
    /* logic */
}

Apart from the difficulty in writing i = 5 - 1; that is i = 4;, are there any other considerations?

like image 347
Jay Avatar asked Dec 03 '22 01:12

Jay


1 Answers

It's usually recommended to concentrate on making code as clear and as logical as possible, without worrying about micro-optimizations or other factors. In your case, the first one is the better choice, since most programmers are more used to traverse an array in that order.

Both versions will have the same result (given that they're implemented correctly) and will have exactly the same run time.

EDIT: @Zane mentioned in a comment that looping backwards to zero was faster some time ago. It was, the reason for it was that comparing a variable to zero was faster. Given that computers were much much slower those days, such optimizations were encouraged. Those days are indeed over...

like image 112
Radu Murzea Avatar answered Dec 05 '22 14:12

Radu Murzea