2017-08-06 86 views
1

當前的.NET編譯器是否以不同的方式對待它們?迭代ToList方法vs ToList數據保存在內存中

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

VS

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

的可能的複製[?通過函數結果循環時如何工作的foreach(https://stackoverflow.com/questions/1632810/ how-do-foreach-work-when-while-through-function-results) –

+0

前者的唯一好處是如果你想用'stuff'變量來做其他事情。對於你的代碼,你可以使用後者。 – mjwills

回答

1

如果啓用編譯器的優化隨後的代碼兩組將編譯到相同的IL。例如,這是針對主方法的IL輸出使用LinqPad時:

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