For 和 Foreach 的比较

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

C#代码:

public int LoopTest()

{

int s=0;

int[] array={2,3,4,5,6,7,8,9};

for(int k=0;k<=7;k++)

{

s+=array[k];

}

foreach(int a in array)

{

s+=a;

}

return s;

}

IL代码:

.method public hidebysig instance int32 LoopTest() cil managed

{

// 代码大小 78 (0x4e)

.maxstack 3

.locals init ([0] int32 s,

[1] int32[] 'array',

[2] int32 k,

[3] int32 a,

[4] int32 CS$00000003$00000000,

[5] int32[] CS$00000007$00000001,

[6] int32 CS$00000008$00000002)

IL_0000: ldc.i4.0

IL_0001: stloc.0

IL_0002: ldc.i4.8

IL_0003: newarr [mscorlib]System.Int32

IL_0008: dup

IL_0009: ldtoken field valuetype '<PrivateImplementationDetails>'/'$$struct0x6000002-1' '<PrivateImplementationDetails>'::'$$method0x6000002-1'

IL_000e: call void [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array,

valuetype [mscorlib]System.RuntimeFieldHandle)

IL_0013: stloc.1

IL_0014: ldc.i4.0

IL_0015: stloc.2

IL_0016: br.s IL_0022 //for 开始的地方

IL_0018: ldloc.0

IL_0019: ldloc.1

IL_001a: ldloc.2

IL_001b: ldelem.i4

IL_001c: add

IL_001d: stloc.0

IL_001e: ldloc.2

IL_001f: ldc.i4.1

IL_0020: add

IL_0021: stloc.2

IL_0022: ldloc.2

IL_0023: ldc.i4.7

IL_0024: ble.s IL_0018 //for 结束的地方

IL_0026: ldloc.1 //foreach 从这里开始

IL_0027: stloc.s CS$00000007$00000001

IL_0029: ldc.i4.0

IL_002a: stloc.s CS$00000008$00000002

IL_002c: br.s IL_003e

IL_002e: ldloc.s CS$00000007$00000001

IL_0030: ldloc.s CS$00000008$00000002

IL_0032: ldelem.i4

IL_0033: stloc.3

IL_0034: ldloc.0

IL_0035: ldloc.3

IL_0036: add

IL_0037: stloc.0

IL_0038: ldloc.s CS$00000008$00000002

IL_003a: ldc.i4.1

IL_003b: add

IL_003c: stloc.s CS$00000008$00000002

IL_003e: ldloc.s CS$00000008$00000002

IL_0040: ldloc.s CS$00000007$00000001

IL_0042: ldlen

IL_0043: conv.i4

IL_0044: blt.s IL_002e //foreach结束的地方

IL_0046: ldloc.0

IL_0047: stloc.s CS$00000003$00000000 //此乃自动生成的一个变量,保存返回值,void时没有

IL_0049: br.s IL_004b

IL_004b: ldloc.s CS$00000003$00000000

IL_004d: ret

} // end of method Class1::LoopTest

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航