When I started using C#, mainly because of XNA one of the things I got used to write is foreach loops instead of for, seemed easier and it’s a much cleaner code. Doing almost the same thing as a for loop I never really bother to see the differences, almost everyone in their XNA examples used it instead.
Today I decided to see the differences between them:
FOR
int[] values = new int[1];
int total = 0;
for(int i = 0; i < values.Length; i++)
{
total += values[i];
}
FOREACH
int[] values = new int[1];
int total = 0;
foreach(int i in values )
{
total += i;
}
In variable declaration, foreach has five variable declarations (three Int32 integers and two arrays of Int32) while for has only three (two Int32 integers and one Int32 array). When it goes to loop through, foreach copies the current array to a new one for the operation. While for doesn’t care of that part.
After the compiler interpretation to Assembly we get this:
FOR
cmp dword ptr [eax+4],0 i
jle 0000000F
mov ecx,dword ptr [eax+edx*4+8]
inc edx
cmp esi,dword ptr [eax+4]
jl FFFFFFF8
FOREACH
cmp esi,dword ptr [ebx+4] i
jl FFFFFFE3
cmp esi,dword ptr [ebx+4]
jb 00000009
mov eax,dword ptr [ebx+esi*4+8]
mov dword ptr [ebp-0Ch],eax
mov eax,dword ptr [ebp-0Ch]
add dword ptr [ebp-8],eax
inc esi
cmp esi,dword ptr [ebx+4]
jl FFFFFFE3
As you can see we end up with much more instructions.
Some simple tests gives these results:
Using Objects | Using Integers | |
---|---|---|
FOR | FOREACH | |
ArrayList – 2147483 items | 88.6 | 115.9 |
generic collection – 2147483 items | 84.4 | 87.1 |
Array – 2147483 items | 48.1 | 49.8 |
*Time is in milliseconds.
So what I’ve done after this was to replace some heavy foreach code on my engine by for loops. I guess small things can be neglected but it’s always nice to know where bottlenecks may happen.