在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

其他回答

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

我认为在大多数情况下,for比foreach稍微快一点,但这真的没有抓住重点。有一件事我没有看到提到的是,在你正在谈论的场景中(即,一个大容量的web应用程序),for和foreach之间的性能差异对站点的性能没有影响。你将受到请求/响应时间和DB时间的限制,而不是v. foreach。

也就是说,我不理解你对foreach的厌恶。在我看来,foreach在任何一个都可以使用的情况下通常更清楚。我通常为需要以某种丑陋的、非标准的方式遍历集合的情况而保留。

我认为使用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最后

两者之间不太可能有巨大的性能差异。与往常一样,当面对“哪个更快?”的问题时,您应该始终认为“我可以测量这个”。

在循环体中编写两个做相同事情的循环,执行并计时,并查看速度的差异。使用一个几乎为空的主体和一个与您实际要做的类似的循环主体来执行此操作。还可以尝试使用您正在使用的集合类型,因为不同类型的集合可能具有不同的性能特征。

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

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