Comparison of Fors and Foreach

zhaozj2021-02-16  86

C # code: 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 code: .method public hidebysig instance int32 looptest () CIL managed {// code size 78 (0x4e) .maxstack 3 .locals init ([0] int32 s, [1] int32 [] 'array', [2] int32 K, [3] int32 a, [4] int32 cs $ 00000003000000, [5] int32 [] cs $ 0000000 00000001, [6] INT32 CS $ 00000008 $ 0000000) 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 '

'/' $ Struct0x6000002-1 ''

'::' $$ 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 the start of the place

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 ended

IL_0026: ldloc.1 // foreach begins here

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: Addil_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 End of the place

IL_0046: LDLOC.0

IL_0047: STLOC.S $ 100003 $ 00000000 // This is an automatically generated variable, save the return value, noid

IL_0049: Br.s IL_004B

IL_004B: LDLOC.S CS $ 00000003 $ 00000000

IL_004D: RET

} // end of method class 1 :: looptest

转载请注明原文地址:https://www.9cbs.com/read-13565.html

New Post(0)