01:58 pm - .NET JIT wonders Once upon a time there was a difference between 'for' and 'foreach': http://www.codeproject.com/Articles/6759/FOREACH-Vs-FOR-C Well, the article is now 8 years old, and instead of ugly and clumsy .NET 1.1 we have .NET 4.0 with tons of useful features and handfuls of sweet syntax sugar. But had anything change under the hood? Let us repeat the test from the article. Here is the C# code:
class Program {
static void testFor() {
int[] myInterger = new int[1];
int total = 0;
for (int i = 0; i < myInterger.Length; i++) {
total += myInterger[i];
}
}
static void testForeach() {
int[] myInterger = new int[1];
int total = 0;
foreach (int i in myInterger) {
total += i;
}
}
static void Main(string[] args) {
testFor();
testForeach();
}
}
}
OK, following the original article the next step is to disassemble actual binary code created by JIT compiler. This one is for 'for'
; Function ForForeach.Program.testFor (code starts at 0x2700a0).
; Offsets are relative to function start.
push ebp
mov ebp,esp
mov edx,1
mov ecx,6B4F4186h
call FFF52103
mov ecx,eax
xor edx,edx
mov eax,dword ptr [ecx+4]
test eax,eax
jle 0000000B
cmp dword ptr [ecx+edx*4+8],eax
inc edx
cmp eax,edx
jg FFFFFFF9
pop ebp
ret
And this is 'foreach'
; Function ForForeach.Program.testForeach (code starts at 0x2700e0).
; Offsets are relative to function start.
push ebp
mov ebp,esp
mov edx,1
mov ecx,6B4F4186h
call FFF520C3
mov ecx,eax
xor edx,edx
mov eax,dword ptr [ecx+4]
test eax,eax
jle 0000000B
cmp dword ptr [ecx+edx*4+8],eax
inc edx
cmp eax,edx
jg FFFFFFF9
pop ebp
ret
Judging from this huge difference in the disassembled samples I'm able to say that Microsoft had definitely introduced some improvements in the most recent versions on .NET framework and, therefore, the article I've mentioned in the beginning is no longer relevant.
|