對於一個簡單的裸數組,for循環往往會產生稍小的IL。比較
static int[] array = new int[100];
static void UseForLoop() {
for (int i = 0; i < array.Length; ++i) {
Console.WriteLine(array[i]);
}
}
static void UseForeachLoop() {
foreach (int i in array) {
Console.WriteLine(i);
}
}
從2010 VS產生IL的下面套,默認釋放配置:
.method private hidebysig static void UseForLoop() cil managed
{
.maxstack 2
.locals init (
[0] int32 i)
L_0000: ldc.i4.0
L_0001: stloc.0
L_0002: br.s L_0014
L_0004: ldsfld int32[] ConsoleApplication5.Program::array
L_0009: ldloc.0
L_000a: ldelem.i4
L_000b: call void [mscorlib]System.Console::WriteLine(int32)
L_0010: ldloc.0
L_0011: ldc.i4.1
L_0012: add
L_0013: stloc.0
L_0014: ldloc.0
L_0015: ldsfld int32[] ConsoleApplication5.Program::array
L_001a: ldlen
L_001b: conv.i4
L_001c: blt.s L_0004
L_001e: ret
}
.method private hidebysig static void UseForeachLoop() cil managed
{
.maxstack 2
.locals init (
[0] int32 i,
[1] int32[] CS$6$0000,
[2] int32 CS$7$0001)
L_0000: ldsfld int32[] ConsoleApplication5.Program::array
L_0005: stloc.1
L_0006: ldc.i4.0
L_0007: stloc.2
L_0008: br.s L_0018
L_000a: ldloc.1
L_000b: ldloc.2
L_000c: ldelem.i4
L_000d: stloc.0
L_000e: ldloc.0
L_000f: call void [mscorlib]System.Console::WriteLine(int32)
L_0014: ldloc.2
L_0015: ldc.i4.1
L_0016: add
L_0017: stloc.2
L_0018: ldloc.2
L_0019: ldloc.1
L_001a: ldlen
L_001b: conv.i4
L_001c: blt.s L_000a
L_001e: ret
}
..但有關鍵部位,環,基本上是相同的。正如其他人所說,這也是一種微觀優化。來自這兩種方法的JIT'd x86可能會相同,除非您使用複雜的枚舉器遍歷複雜集合,但即使在實際示例中,差異也不大。
我會使用一個更易讀 - 如果速度是真的那麼多的問題,贊成for循環,但你可能會從算法優化得到更好的結果。
老實說,這不會有問題,你的性能問題將在別處 – BrokenGlass 2011-01-11 18:23:43
你有沒有嘗試過自己測量它? – 2011-01-11 18:24:21
看看這個:http://stackoverflow.com/questions/1124753/for-vs-foreach-loop-in-c – 2011-01-11 18:24:36