Vincent
Vincent

Reputation: 60451

C++ 2011 : range-based loop unrolling?

I wonder if C++ compilers will unroll range-based loop the same way they currently do for "normal" loops to maximize performance or in some case range-based loops will be slower than normal loops?

Upvotes: 2

Views: 698

Answers (2)

K-ballo
K-ballo

Reputation: 81389

Chances are compilers translate range-based for loops into their regular loop counterpart, so I would expect them to be equivalent.

Upvotes: 5

P.P
P.P

Reputation: 121417

for range-based loop is equivalent to:

{
  auto && __range = ( /expression/ );
  for (auto __begin = begin(__range),
            __end   = end(__range);
       __begin != __end;
       ++__begin) {
    /declaration/ = *__begin;
    /statement/
  }
}

If compiler knows the number of iterations and it can solve the loop dependencies or loops are independent, then compiler is free to un-roll.

In general, loop unrolling is going to improve performance only for smaller loops. So, IMO, it does not matter whether range-based loops are unrolled or not. You can certainly benchmark with -O3 and -funroll-loops and relevant options to see if there's indeed any difference between two.

Upvotes: 7

Related Questions