I ++ or i-- in a for loop?

When writing a for loop where both initial and final conditions are known, which method is better? Let's say I have to repeat the loop to add elements of an array of size 5. In this case, which of the following would be more efficient in terms of runtime? Which one will give the best performance?

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

OR

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

Besides the difficulty of writing i = 5 - 1; << 24>, are there any other considerations?

+4
source share
7 answers

It is generally recommended that you focus on making the code as clear and logical as possible without worrying about micro-optimization or other factors. In your case, the first option is the best choice, since most programmers use it more to move the array in this order.

Both versions will have the same result (given that they are implemented correctly) and will have exactly the same runtime.

EDIT: @Zane mentions in a comment that the loop back to zero was faster some time ago. This was due to the fact that comparing a variable with zero was faster. Given that computers were much slower in those days, this optimization was encouraged. These days are really over ...

+9
source

There is something wrong with the code. The first cycle is good, but the second is not executed yet: it works 0 times. It should be

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

In addition, if you ask which is better, this is your choice with which you are comfortable. For me, I feel that the first one is more convenient.

+4
source

In most cases, this does not matter, but there are some situations in which unobvious side effects may occur. Consider the loop:

for(int i = 0; i < strlen(str); i++) {/* do stuff on i-th elem */} . Here, at each iteration, strlen (str) will be reevaluated (if not optimized by the compiler), even if it is completely unnecessary; the programmer most likely did not even think about it. It might be worth replacing the loop:

for(int i = strlen(str); i > 0; i--) {/* do stuff on i-th elem */} . Here the string length will be evaluated only once.

Of course, in the first cycle the problem can be avoided by using an additional variable to store the length of the string, but this is just an extra noise that is not related to the program logic.

+2
source

The most obvious answer: which of them has the semantics that you want? They visit the objects in a different order.

Generally, if there are no other considerations, people expect ascending, and this is what you should use when visiting sites. In C ++ it is much more idiomatic to use iterators for this. Normal iterators are visited in ascending order, reverse iterators in descending order. If you clearly don't need to go down, you should use regular iterators. This is what people expect, and when you use reverse iterators, the first thing the reader asks is why. In addition, I did not measure it, but it would not surprise me if ordinary iterators were faster than iterators on the contrary. In Java, iterators are also idiomatic, and you don't have reverse iterators.

If I need a decreasing order when visiting, I will use a while loop (unless I have reverse iterators that do this for me); I'm something like:

 int index = numberOfElements; while ( index != 0 ) { -- index; // ... } 

much more readable (and easier to get right) than any of the alternatives.

If you do not visit objects, but simply think that descending seems more natural to me: the control variable contains the number of times left. And since the account is never used as an index, there is no problem that it will be one of the indices, and you can use the traditional for .

 for ( int count = numberOfTimes; count != 0; -- count ) { // ... } 

But it really is a matter of style; I have seen many upstream cycles for this as well.

+2
source

I believe that most programmers will be able to quickly understand your code using the first method (i ++). Unless you need to process the array in reverse, I would stick with your first method. As for performance, I believe that for any solution there will be little or no profit at all.

You might also consider using the for..each ( for ) syntax, which is pretty neater.

  int[] x = {1,2,3,4,5}; for(int y: x){ System.out.println(y); } 
0
source

I would say that the loop with i ++ is easier to understand. Also, going backward may make suboptimal use of the processor cache, but usually compilers / virtual machines are smarter than that.

0
source

An incremental cycle of a cycle or a decremented cycle is selected based on how you want to use the counter variable or how good it looks.

  • if you access some array in ascending order , decrement is used for the loop

    for (i = 0; i < 5; i++) { arr[i]; }

  • If you are accessing some array or list in descending order , incremental for loop is used

    for (i = 5; i > 0 ; i--) { arr[i-1]; }

  • if the counter number does not matter for the available value, then the code is readable . And incremental for the loop looks more attractive.

0
source

Source: https://habr.com/ru/post/1444773/


All Articles