这更快:for或foreach

mun*_*nna 0 c# generics

可能重复:
对于C#中的vs foreach循环

让我们说我有一个集合

List <Foo> list = new List <Foo>();

现在哪个愚蠢的循环运行得更快,原因如下:

for(int i = 0; i <list.Count; i ++)

要么

foreach(Foo foo列表中)

dec*_*one 5

这取决于 :

For For循环,它位于How much time does it take to evaluate the value oflist.Count or whatever value is provided in conditionHow much time does it take to reference item at specific index.

对于Foreach循环,它取决于How much time it takes for an iterator to return a value.

对于上面的示例,应该没有任何区别,因为您使用的是标准List类.