Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

like image 774
ayush gupta Avatar asked May 17 '20 19:05

ayush gupta


Video Answer


1 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

like image 105
0___________ Avatar answered Sep 28 '22 19:09

0___________