Reputation: 43
Consider these two pieces of code:
float arr1[4], arr2[4];
//Do something here with arr1 and arr2
for (int i = 0; i < 4; i++)
arr1[i] += arr2[i];
-
float arr1[4], arr2[4];
//Do something here with arr1 and arr2
arr1[0] += arr2[0];
arr1[1] += arr2[1];
arr1[2] += arr2[2];
arr1[3] += arr2[3];
Assuming I'm working with larger arrays of a known fixed size, would the first have any performance impact over the second?
Upvotes: 2
Views: 652
Reputation: 8215
Assuming no compiler optimizations, then the for
loop is unavoidably 'slower'. Although both approaches are O(n), the for
loop has a larger constant because of the loop overhead.
Loop unrolling is a reasonable time-space trade-off for small arrays, and may actually be a space gain for really small arrays.
But doing it manually introduces many, roughly n
, opportunities for human error both during the initial (inevitable) cut and paste of creating the many lines of code needed to do it manually, and then when changes need to be made later to the "loop body".
Generally, loops are preferable for reasons of maintenance and readability. They also more clearly convey the intent of the code.
Finally, for large arrays, small loop bodies, and particular target architectures, the processor's cache comes into play. In many cases the entire loop will fit in the cache, making it much faster than a long list of instructions.
Let the compiler worry about optimizing.
Upvotes: 3
Reputation: 12058
It depends how the loop is constructed. In case of short loops, that don't have much code inside, this can be done automatically by the compiler. It is known as loop unrolling.
Is it slower? Faster? There is no one, right answer - always profile your code. It may be faster to do it manually, because loops are implemented as conditional jumps. So it may be faster to manually go through it, because code will be executed "in order", instead of jumping to the same location multiple times.
Consider following code:
int main()
{
int sum = 0;
int values[4] = { 1, 2, 3, 4 };
for(int n = 0; n < 4; ++n)
sum += values[n];
return 0;
}
Following assembly will be generated for for
loop:
Now, let's change it to manual approach:
int main()
{
int sum = 0;
int values[4] = { 1, 2, 3, 4 };
sum += values[0];
sum += values[1];
sum += values[2];
sum += values[3];
return 0;
}
Result:
Which one is better? Which one is faster? Hard to say. Code without jumps and conditions may be faster, but unrolling loops, that are to complex may result in code bloating.
So, what is my answer? Find out yourself.
Upvotes: 0