在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

(编辑)

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


当前回答

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

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

数组迭代使用foreach循环:

And - list迭代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。

我认为使用Parallel.ForEach()以及ConcurrentDictionary或ConcurrentBag会更快

下面是Parallel.ForEach()的例子

        var primeNumbers = new ConcurrentBag<T>();
        Parallel.ForEach(numbers, number =>
        {
            if (IsPrime(number))
            {
                primeNumbers.Add(number);
            }
        });

And

 var productImage = new ConcurrentDictionary<int,ResultModel>();
  Parallel.ForEach(pendingActiveImagesBatch, pictureItem =>
  {                           
     productImage.TryAdd(pictureItem.Id,pictureItem));
  });

引用平行。ForEach 参考ConcurrentDictionary最后

我不期望任何人发现两者之间的“巨大”性能差异。

我想答案取决于您试图访问的集合是否具有更快的indexer访问实现或更快的IEnumerator访问实现。由于IEnumerator经常使用索引器,并且仅保存当前索引位置的副本,因此我希望枚举器访问至少与直接索引访问一样慢或更慢,但不会慢太多。

当然,这个答案没有解释编译器可能实现的任何优化。

除非您处于特定的速度优化过程中,否则我会建议使用产生最容易阅读和维护代码的方法。

如果已经设置了迭代器,比如其中一个集合类,那么foreach是一个很好的简单选项。如果你迭代的是一个整数范围,那么for可能更简洁。