c# – .Net – 什么时候List.ForEach优先于标准的foreach循环?
发布时间:2020-12-16 00:11:47 所属栏目:百科 来源:网络整理
导读:通用列表类具有.ForEach(Action T action)方法.现在我已经完成了一些关于它们如何表现的简单时间,似乎通用ForEach是较差的表演者. (Snippet Compiler Friendly)代码如下 – public static class timer{ public static long foreachloop = 0; public static l
通用列表类具有.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更清楚. 我已经建议这样的方法可以被认为是a fix for the classic closure-over-loop-variable bug. 但在实践中,我只是更好地发现了这样的错误. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |