![](/img/trans.png)
[英]When would I use List<T>.ForEach over a native foreach loop?
[英].Net - When is List<T>.ForEach prefered over a standard foreach loop?
通用列表類具有.ForEach(Action<T> action)
方法。 現在我已經完成了一些關於它們如何表現的簡單時間,似乎通用ForEach是較差的表演者。 (Snippet Compiler Friendly)代碼如下 -
public static class timer{
public static long foreachloop = 0;
public static long Gforeachloop = 0;}
public class something{
public List<string> myStrings = new List<string>();
public something()
{
for(int i = 1; i<=5000000;i++)
{
myStrings.Add(i.ToString());
}
}}
public class cls1{
private static List<string> Strings = new List<string>();
private static List<string> OtherStrings = new List<string>();
public static void RunSnippet()
{
something s = new something();
Stopwatch watch = new Stopwatch();
watch.Start();
foreach(string x in s.myStrings)
{
Strings.Add(x);
}
watch.Stop();
timer.foreachloop = watch.ElapsedMilliseconds;
watch.Reset();
watch.Start();
s.myStrings.ForEach(delegate(string n){OtherStrings.Add(n);});
s.myStrings.Clear();
watch.Stop();
timer.Gforeachloop = watch.ElapsedMilliseconds;
WL("FOREACH-"+timer.foreachloop + ",Count = " + Strings.Count);
WL("GFOREACH-"+timer.Gforeachloop + ",Count = " + OtherStrings.Count);
}
#region Helper methods
public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
FOREACH出現在177ms,GFOREACH出現在707ms。
現在我猜這是使用它的一個很好的理由,但我想不出一個。 顯然性能不是原因,所以問題是何時它是最佳選擇?
提前致謝。
這篇來自Eric Lippert的博客文章給出了背景:
http://blogs.msdn.com/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx
他正在討論擴展方法的常見建議, IEnumerable<T>
做同樣的事情,但哲學上的反對也適用於List<T>.ForEach
。
這表明也許這種方法從來都不是一個好主意,雖然它看起來很“酷”。 使用foreach
更清楚。
我已經建議這樣的方法可以被認為是對經典的閉環過程變量bug的修復 。
但在實踐中,我只是更好地發現了這樣的錯誤。
當它看起來更整潔。
根本不是開玩笑。 真的,我的意思是。 在您的情況下,使用更易讀的樣式。 例如,如果您只想在每個項目上調用方法,例如:
list.ForEach(Console.WriteLine);
這種風格更適合。 但是,如果你有一百行作為循環體,或者你有嵌套循環和控制流結構,舊樣式看起來更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.