在c# / VB.NET/。哪个循环运行得更快,for还是foreach?

自从很久以前我读到for循环比foreach循环工作得快,我就认为它适用于所有集合、泛型集合、所有数组等。

我搜索了谷歌,找到了几篇文章,但大多数都是不确定的(阅读文章评论),而且是开放式的。

理想的情况是列出每种情况以及最佳解决方案。

例如(这只是一个例子):

用于迭代1000+的数组 字符串- for比foreach好 对于迭代IList(非泛型)字符串- foreach更好 比

在网上找到了一些相同的参考资料:

由Emmanuel Schanzer撰写的原创文章 CodeProject FOREACH Vs. FOR 博客——去博客还是不去博客,这是个问题 ASP。NET论坛- NET 1.1 c# for vs foreach

(编辑)

除了可读性之外,我对事实和数据真的很感兴趣。在某些应用中,最后一英里的性能优化确实很重要。


当前回答

完全禁止使用for循环之类的东西似乎有点奇怪。

这里有一篇有趣的文章,介绍了两个循环之间的许多性能差异。

我个人会说,我发现foreach比for循环更具可读性,但你应该使用最好的方法来完成手头的工作,如果for循环更合适的话,就不必编写额外的长代码来包含foreach循环。

其他回答

你可以在Deep .NET - part 1迭代中读到它

它覆盖了从。net源代码一直到反汇编的结果(没有第一次初始化)。

数组迭代使用foreach循环:

And - list迭代foreach循环:

最终结果是:

请记住,for循环和foreach-循环并不总是等价的。如果列表更改,列表枚举器将抛出异常,但使用普通的for循环并不总是会得到该警告。如果列表在错误的时间更改,甚至可能会得到不同的异常。

for是否比foreach快确实不是重点。我非常怀疑选择其中之一会对你的表现产生重大影响。

优化应用程序的最佳方法是对实际代码进行分析。这将精确地找出占用最多工作/时间的方法。首先优化它们。如果性能仍然不能接受,请重复上述步骤。

一般来说,我建议不要进行微观优化,因为它们很少会产生任何显著的收益。唯一的例外是在优化确定的热门路径时(即,如果您的分析确定了一些高度使用的方法,那么广泛地优化这些方法可能是有意义的)。

Jeffrey Richter在techhed 2005上说:

"I have come to learn over the years the C# compiler is basically a liar to me." .. "It lies about many things." .. "Like when you do a foreach loop..." .. "...that is one little line of code that you write, but what the C# compiler spits out in order to do that it's phenomenal. It puts out a try/finally block in there, inside the finally block it casts your variable to an IDisposable interface, and if the cast suceeds it calls the Dispose method on it, inside the loop it calls the Current property and the MoveNext method repeatedly inside the loop, objects are being created underneath the covers. A lot of people use foreach because it's very easy coding, very easy to do.." .. "foreach is not very good in terms of performance, if you iterated over a collection instead by using square bracket notation, just doing index, that's just much faster, and it doesn't create any objects on the heap..."

按需网络直播: http://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?EventID=1032292286&EventCategory=3&culture=en-US&CountryCode=US

我之前测试过,结果是for循环比foreach循环快得多。原因很简单,foreach循环首先需要为集合实例化一个IEnumerator。