Which method is better for incrementing and traversing in a loop in C

Viewed 184

These are example of incrementing each element of an array by 10.

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

or

for (i = 0; i< 100; i+=2){
    arr[i] += 10;
    arr[i+1] += 10;
}

which is the efficient way to solve this problem out of these these two in C language?

3 Answers

As @JeremyRoman stated compiler will be better than the humans optimizing the code.

But you may make its work easier or tougher. In your example the second way prevents gcc from unrolling the loops.

So make it simple, do not try to premature micro optimize your code as result might be right opposite than expected

https://godbolt.org/z/jYcLpT

Let's look at better and efficient outside of run-time performance1.

Bug!

Only 3 or 4 lines of code and the one with 4 is incorrect. What if arr[] and ar[] both existed? the compiler would not complain, yet certainly incorrect code.

//ar[i+1] += 10;
arr[i+1] += 10;

Coding

The below wins. Short and and easy to code. No concern about if arr[i+1] += 10; access arr[100]

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

Review

The below wins. Clear, to the point. I had to review the other more to be clear of its correctness - inefficient review time. Defense-ability - I'd have no trouble defending this code.

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

Maintenance

The below wins. Change i < 100 to i < N and this code is fine, the other can readily break.

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

Optimization possibilities

The below wins. Compilers do a fine job at optimizing common idioms. The 2nd poses more analyses and a greater chance the compiler will not optimize well.

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

Score

Outside of performance:

5 to 0


1 Notice OP never explicitly stated to view this only as run-time performance. So let use consider various ideas of better.

Related