0

I was wondering if this code

for (int i=0; i <= n; i++)
{
    someArray[i] = i;
}

will be slower than initializing array line by line like this

someArray[0] = 0;
someArray[1] = 1;
.
.
.
someArray[n] = n;

It seems like if there is no compiler optimization for this, the for loop would be slower since it need to create a new variable i, check the conditional statement and increment i. I was wondering if there is actually a compiler time optimization that optimizes scenarios like this.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Saik
  • 993
  • 1
  • 16
  • 40
  • 1
    Note that this is the same as loop unrolling. – Sergey Kalinichenko May 24 '17 at 03:06
  • 2
    This is called loop unrolling and is something compilers do. Just write the loop and trust that optimizer knows what it is doing (it can even do things like vectorizing it). If you're concerned you can always profile or look at the assembly. – NathanOliver May 24 '17 at 03:07
  • And note: Sometimes, the loop is the best way to go. for loops with predictable conditions are usually handled just fine by the CPU's branch predictor; everything ends up in a tight loop that's wholly in L1 cache, speculative execution means it behaves as if it weren't a loop at all. By contrast, unrolling a sufficiently large loop might mean you're moving more code around, avoiding branch costs you never pay in exchange for additional bus bandwidth you need elsewhere. – ShadowRanger May 24 '17 at 03:10
  • Thanks guys, I should invest some time and learn how the compilers actually work. – Saik May 24 '17 at 03:11
  • Actually this is a slight bit more involved than just "how compilers work" – Passer By May 24 '17 at 03:14
  • Also, side-note: For this specific case, C++11 [added `std::iota`](http://en.cppreference.com/w/cpp/algorithm/iota); the stdlib is probably the best way to do this if you're worried, since it can microoptimize (if necessary) by architecture. – ShadowRanger May 24 '17 at 03:14
  • @ShadowRanger Thanks for that suggestion. I will definitely look into that, but I was asking about the loops in general and not about array initiation in particular. Array initialization was just the first example to demonstrate my question that popped out in my mind. – Saik May 24 '17 at 03:29

1 Answers1

0

compiler can do loop unroll to make it faster.

iceraj
  • 359
  • 1
  • 5