在 C#/VB.NET/.NET 中,for
或 foreach
哪个循环运行得更快?
自从我读到 for
循环比 foreach
循环工作得更快之后,我就知道了 long time ago我假设它适用于所有集合、通用集合、所有数组等。
我搜索了 Google 并找到了几篇文章,但其中大部分是不确定的(阅读文章评论)并且是开放式的。
理想的做法是列出每种情况并列出相应的最佳解决方案。
例如(只是它应该如何的一个例子):
- 用于迭代 1000+ 的数组
字符串 -
for
优于foreach
- 用于遍历
IList
(非通用)字符串 -foreach
更好 比为
在网络上找到了一些相同的引用资料:
- Original grand old article by Emmanuel Schanzer
- CodeProject FOREACH Vs. FOR
- Blog - To
foreach
or not toforeach
, that is the question - ASP.NET forum - NET 1.1 C#
for
vsforeach
[编辑]
除了它的可读性方面,我对事实和数字非常感兴趣。在某些应用程序中,压缩的最后一英里性能优化确实很重要。
最佳答案
Patrick Smacchia blogged about this上个月,得出以下结论:
- for loops on List are a bit more than 2 times cheaper than foreach loops on List.
- Looping on array is around 2 times cheaper than looping on List.
- As a consequence, looping on array using for is 5 times cheaper than looping on List using foreach (which I believe, is what we all do).
关于c# - 在 .NET 中,哪个循环运行得更快, 'for' 还是 'foreach'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/365615/