Assigning `array[i]` to variable inside loop on `i` , what pros and cons it gives in C?

67 views Asked by At

There is some abstract loop that loops through array, and processes every single element without dependency of it's place in array. Element value is checked against conditions many times.

Adding int value = arr[i] will help reading the code, and theoretically, will take sizeof(int) memory away.

Will it boost performance? Or will compiler optimize it?

I know, early-optimization is very very bad, that is theoretical question.

int arr[10];
...
for (int i = 0; i < 10; i++)
{
   if (arr[i] > 2) 
   {
     if (arr[i] < 100)
     {
       do_smth1(arr[i]);
     }
     else if (arr[i] > 500 && arr[i] < 1000)
     {
       do_smth2(arr[i]);
     }
     else
     {
       do_smth3(arr[i]);
     }
   }
   else 
   {
     do_smth4(arr[i]);
   }
}
1

There are 1 answers

0
chux - Reinstate Monica On BEST ANSWER

Will it boost performance?

No.

Or will compiler optimize it?

Yes. If not, get a better compiler.

... and theoretically, will take sizeof(int) memory away.

No, not certainly.


With such candidate linear optimizations, coding for clarity is overwhelming the best option.

Use your valuable coding time to improve bigger picture items and let the compiler handle the small stuff.

See also Is premature optimization really the root of all evil?.


Warning: Compilers today recognize many common idioms and emit efficient code. Should you code in an uncommon fashion, in order to "improve" things, the compiler may miss optimizations and then your "improved" code is worse than clear common code.

Instead of trying to outthink the compiler, use it to leverage your productively.