在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

(编辑)

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


当前回答

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

其他回答

我的猜测是,在99%的情况下,它可能并不重要,所以为什么要选择更快的,而不是最合适的(最容易理解/维护)?

在大多数情况下,其实没有什么区别。

通常,当你没有显式的数值索引时,你总是必须使用foreach,而当你实际上没有可迭代集合时,你总是必须使用for(例如,在上三角形的二维数组网格上迭代)。在某些情况下,你可以做出选择。

有人可能会说,如果代码中开始出现神奇的数字,for循环可能会更难维护。你对不能使用for循环而不得不构建一个集合或使用lambda来构建子集合感到恼火应该是正确的,因为for循环已经被禁止了。

在处理对象集合的情况下,foreach更好,但如果要增加一个数字,则for循环更好。

注意,在最后一种情况下,你可以这样做:

foreach (int i in Enumerable.Range(1, 10))...

但它并没有表现得更好,它实际上比for的表现更差。

我需要使用三个嵌套循环(在List<MyCustomType>上)对一些大型数据进行解析。我想,使用Rob Fonseca-Ensor上面的帖子,比较for和foreach的区别会很有趣。

区别在于: foreach(三个foreach嵌套,如foreach{foreach{forech{}}})在171.441秒内完成了这项工作,而for (for{for{for{}}})在158.616秒内完成了这项工作。

现在13秒大约减少了13%的时间,这对我来说有点重要。然而,foreach绝对比使用三个索引for…

这可能取决于您枚举的集合类型及其索引器的实现。一般来说,使用foreach可能是一种更好的方法。

而且,它可以与任何IEnumerable一起工作,而不仅仅是与索引器一起工作。