Is there a speed difference at execution between writing n following operations or using a for looping from 0 to n?

Viewed 99

Let's say I have to do the same operation op on the n+1 elements of an array arr.

Is there a difference of speed at execution between :

op(arr[0]);
op(arr[1]);
...
op(arr[n]);

and

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

Or is the compiler smart enough to detect the for loop (given n is fixed at compile time) and convert it to the linear execution (if it is actually faster)?

1 Answers

is the compiler smart enough to ....

Yes. Many compilers are far better at such micro optimizations that coders.

This loop or unrolled loop micro-optimization depends on the possessor - some will be faster one way, some the other. Best to code for clarity and let the compiler optimize. If the compiler does not optimize well, more effective to research a new compiler (or its options) than craft code.


Yet for a select situation and with a very knowledgeable coder, crafted code may be better. But that takes time that could be spent with larger efficiency issues.

Problem with crafted code (faster code but looks strange) include: higher maintenance cost, convoluted-ness make for difficult optimization on another platforms, higher bug rate. So the crafted solution may work faster today, yet slower with the next compiler update.

Related