代码规范之循环变量

第一种写法:
        var list=new List<string>(){"str","str","str","str","str"};
    string s = default(string);        
    foreach(var item in list)
    {            
        s = item;
    }

第二种写法:
        var list=new List<string>(){"str","str","str","str","str"};    
    foreach(var item in list)
    {            
        string s=item;
    }

可能会有好多程序员以为第一种写法效率会高一些,事实真的是这样吗?

不是,因为这两种写法最终转变成的IL代码是一样的,它们的IL代码如下

IL_0000:  newobj      System.Collections.Generic.List<System.String>..ctor
IL_0005:  stloc.2     
IL_0006:  ldloc.2     
IL_0007:  ldstr       "str"
IL_000C:  callvirt    System.Collections.Generic.List<System.String>.Add
IL_0011:  ldloc.2     
IL_0012:  ldstr       "str"
IL_0017:  callvirt    System.Collections.Generic.List<System.String>.Add
IL_001C:  ldloc.2     
IL_001D:  ldstr       "str"
IL_0022:  callvirt    System.Collections.Generic.List<System.String>.Add
IL_0027:  ldloc.2     
IL_0028:  ldstr       "str"
IL_002D:  callvirt    System.Collections.Generic.List<System.String>.Add
IL_0032:  ldloc.2     
IL_0033:  ldstr       "str"
IL_0038:  callvirt    System.Collections.Generic.List<System.String>.Add
IL_003D:  ldloc.2     
IL_003E:  stloc.0     
IL_003F:  ldloc.0     
IL_0040:  callvirt    System.Collections.Generic.List<System.String>.GetEnumerator
IL_0045:  stloc.3     
IL_0046:  br.s        IL_0050
IL_0048:  ldloca.s    03 
IL_004A:  call        System.Collections.Generic.List<System.String>.get_Current
IL_004F:  stloc.1     
IL_0050:  ldloca.s    03 
IL_0052:  call        System.Collections.Generic.List<System.String>.MoveNext
IL_0057:  brtrue.s    IL_0048
IL_0059:  leave.s     IL_0069
IL_005B:  ldloca.s    03 
IL_005D:  constrained. System.Collections.Generic.List<>.Enumerator
IL_0063:  callvirt    System.IDisposable.Dispose
IL_0068:  endfinally  

 欢迎加入群:254082423

一起学习讨论asp.net mvc 

posted @ 2014-07-04 11:36  夜郎之西1  阅读(197)  评论(0编辑  收藏  举报