For 和 Foreach 的比较

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 ' '/'$$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 开始的地方
  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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值