这是更快:为或foreach [英] which is faster: for or foreach
问题描述
可能重复:
对于C#中的vs foreach循环
可以说我有一个集合
列表< Foo> list = new List< Foo>();
List < Foo > list = new List< Foo >();
现在哪些愚蠢的循环运行得更快,为什么:
Now which of the foolowing loops would run faster and why:
for(int i = 0; i
for(int i=0; i< list.Count; i++)
或者
or
foreach(列表中的Foo foo)
foreach(Foo foo in list)
推荐答案
它取决于:
对于 For
循环,它是on 需要多少时间来评估
list.Count 的值或条件
和在特定索引处引用项目需要多少时间。
For For
loop, it is on How much time does it take to evaluate the value of
list.Countor whatever value is provided in condition
and How much time does it take to reference item at specific index
.
对于 Foreach code>循环,它取决于
迭代器返回值需要多少时间
。
For Foreach
loop, it depends on How much time it takes for an iterator to return a value
.
对于上面的示例,应该没有任何区别,因为您使用的是标准List类。
For your above example, there should not be any difference because you are using a standard List class.
这篇关于这是更快:为或foreach的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!