3

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)?

Balocre
  • 175
  • 2
  • 10
  • 3
    Look up *loop unrolling* optimization.. – Eugene Sh. Dec 20 '18 at 19:24
  • 4
    Measure, profile, read the generated code. – Some programmer dude Dec 20 '18 at 19:25
  • 1
    Yes.. this is an optimization technique - Unrolling. You can verify by repeating this for large n's. – displayName Dec 20 '18 at 19:25
  • Possible duplicate of [When, if ever, is loop unrolling still useful?](https://stackoverflow.com/questions/2349211/when-if-ever-is-loop-unrolling-still-useful) – AmourK Dec 20 '18 at 19:26
  • @pmg that's an error from my part, I'll correct the code – Balocre Dec 20 '18 at 19:30
  • 1
    @Balocre I'd expect modern compilers to be smart enough. I don't think you should worry about such micro-optimizations, sacrificting readablitiy. That is, unless your program doesn't work fast enough, *and you can prove with time measurements that unrolling the loop manually will help* – HolyBlackCat Dec 20 '18 at 19:34
  • 1
    [Premature optimization is the root of all evil](http://c2.com/cgi/wiki?PrematureOptimization). Even if there's a speed difference, most of the time it's irrelevant, only worry about this if you actually have a performance problem. – Barmar Dec 20 '18 at 20:59

1 Answers1

4

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.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256