foreach与for的性能比较

时间:2022-06-27 19:15:46
string[] strings = new string[] { "str1", "str2", "str3", "str4", "str5", "str6" };
foreach (string s in strings)
{
textBox1.AppendText(s + "\r\n");
}

IL:

            foreach (string s in strings)
000000e0 nop
000000e1 mov eax,dword ptr [ebp-44h]
000000e4 mov dword ptr [ebp-50h],eax
000000e7 xor edx,edx
000000e9 mov dword ptr [ebp-54h],edx
000000ec nop
000000ed jmp 00000136 //jmp to J1
000000ef mov eax,dword ptr [ebp-54h]
000000f2 mov edx,dword ptr [ebp-50h]
000000f5 cmp eax,dword ptr [edx+4]
000000f8 jb 000000FF         //低于"1个字节全是1"跳转
000000fa call 65C86690         //地址如此之大,应该是个外部call
000000ff mov eax,dword ptr [edx+eax*4+0Ch]
00000103 mov dword ptr [ebp-48h],eax
{
00000106 nop
textBox1.AppendText(s + "\r\n");
00000107 mov eax,dword ptr [ebp-3Ch]
0000010a mov eax,dword ptr [eax+00000140h]
00000110 mov dword ptr [ebp-60h],eax
00000113 mov edx,dword ptr ds:[027420A8h]
00000119 mov ecx,dword ptr [ebp-48h]
0000011c call 64EB50F0           //这个call可能是+导致的 不换行的话IL很短的
00000121 mov dword ptr [ebp-64h],eax
00000124 mov edx,dword ptr [ebp-64h]
00000127 mov ecx,dword ptr [ebp-60h]
0000012a cmp dword ptr [ecx],ecx
0000012c call 636C6414           
00000131 nop
}                    
00000132 nop
00000133 inc dword ptr [ebp-54h]
foreach (string s in strings)
00000136 mov eax,dword ptr [ebp-54h] //Here’s J1
00000139 mov edx,dword ptr [ebp-50h]
0000013c cmp eax,dword ptr [edx+4]
0000013f setl al
00000142 movzx eax,al
00000145 mov dword ptr [ebp-58h],eax
00000148 cmp dword ptr [ebp-58h],0
0000014c jne 000000EF

for的IL:

            for (int i = 0; i != 6; i++)
000000d6 xor edx,edx
000000d8 mov dword ptr [ebp-48h],edx
000000db nop
000000dc jmp 0000011F
{
000000de nop
textBox1.AppendText(strings[i] + "\r\n");
000000df mov eax,dword ptr [ebp-3Ch]
000000e2 mov eax,dword ptr [eax+00000140h]
000000e8 mov dword ptr [ebp-58h],eax
000000eb mov eax,dword ptr [ebp-48h]
000000ee mov edx,dword ptr [ebp-44h]
000000f1 cmp eax,dword ptr [edx+4]
000000f4 jb 000000FB
000000f6 call 65D56690
000000fb mov ecx,dword ptr [edx+eax*4+0Ch]
000000ff mov edx,dword ptr ds:[028620A8h]
00000105 call 64F850F0
0000010a mov dword ptr [ebp-5Ch],eax
0000010d mov edx,dword ptr [ebp-5Ch]
00000110 mov ecx,dword ptr [ebp-58h]
00000113 cmp dword ptr [ecx],ecx
00000115 call 63796414
0000011a nop
}
0000011b nop
for (int i = 0; i != 6; i++)
0000011c inc dword ptr [ebp-48h]
0000011f cmp dword ptr [ebp-48h],6
00000123 setne al
00000126 movzx eax,al
00000129 mov dword ptr [ebp-50h],eax
0000012c cmp dword ptr [ebp-50h],0
00000130 jne 000000DE
}
21个指令3个call

foreach的指令要多很多,应该是foreach慢一些,据<<更锋利的c#>>一书,foreach迭代要比for循环快速,因为这是专门优化的,但是执行效率不能说明问题,c#本机编译完成后,大概是PC上执行最快的local code,c++为什么看起来能节约几倍的执行时间?不是执行速度要有多快,重要是的,本地代码能少点不,搞tmd10倍,想快也快不起来.

那个作者说foreach快,我感觉for快.

foreach不是for的安全版再一个个弹出项吗,这能比for快吗,不过项很多的话,性能也许能超过for....