【问题标题】:Iterating over ToList method vs ToList data held in memory迭代 ToList 方法与内存中保存的 ToList 数据
【发布时间】:2017-08-06 10:22:16
【问题描述】:

当前的 .NET 编译器是否对这些有不同的处理方式?

List<string> stuff = GetSomeStuff();
foreach(string thing in stuff) { ... }

foreach(string thing in GetSomeStuff()) { ... }

【问题讨论】:

标签: c# .net visual-studio


【解决方案1】:

如果您启用编译器优化,那么两组代码都将编译为相同的 IL。例如,这是使用 LinqPad 时 main 方法的 IL 输出:

IL_0000:  ldarg.0     
IL_0001:  call        UserQuery.GetSomeStuff
IL_0006:  callvirt    System.Collections.Generic.List<System.String>.GetEnumerator
IL_000B:  stloc.0     
IL_000C:  br.s        IL_0016
IL_000E:  ldloca.s    00 
IL_0010:  call        System.Collections.Generic.List<System.String>.get_Current
IL_0015:  pop         
IL_0016:  ldloca.s    00 
IL_0018:  call        System.Collections.Generic.List<System.String>.MoveNext
IL_001D:  brtrue.s    IL_000E
IL_001F:  leave.s     IL_002F
IL_0021:  ldloca.s    00 
IL_0023:  constrained. System.Collections.Generic.List<>.Enumerator
IL_0029:  callvirt    System.IDisposable.Dispose
IL_002E:  endfinally  
IL_002F:  ret  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    相关资源
    最近更新 更多