Search code examples
c++arraysfor-looploop-unrolling

Is array initialization in for loop slower then non-for loop initialization in C++


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.


Solution

  • compiler can do loop unroll to make it faster.