的foreach之间,并在C#遍历一个IEnumerable阶级差别 [英] Difference between foreach and for loops over an IEnumerable class in C#

查看:196
本文介绍了的foreach之间,并在C#遍历一个IEnumerable阶级差别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人告诉我,有下面的代码块之间的性能差异。

I have been told that there is a performance difference between the following code blocks.

foreach (Entity e in entityList)
{
 ....
}

for (int i=0; i<entityList.Count; i++)
{
   Entity e = (Entity)entityList[i];
   ...
}



其中,

where

List<Entity> entityList;



我不是CLR期望但我可以告诉他们应该归结为基本相同的代码。没有任何人有混凝土(赫克,我会采取打包脏物)证据的一种方式或其他?

I am no CLR expect but from what I can tell they should boil down to basically the same code. Does anybody have concrete (heck, I'd take packed dirt) evidence one way or the other?

推荐答案

的foreach创建一个实例枚举(从返回的GetEnumerator)和普查员也保持整个foreach循环的过程中的状态。然后,它一再要求对枚举下一步()对象并运行你的代码的每个对象返回。

foreach creates an instance of an enumerator (returned from GetEnumerator) and that enumerator also keeps state throughout the course of the foreach loop. It then repeatedly calls for the Next() object on the enumerator and runs your code for each object it returns.

他们不归结于在任何相同的代码这样,真的,你会看到,如果你写你自己的枚举。

They don't boil down to the same code in any way, really, which you'd see if you wrote your own enumerator.

这篇关于的foreach之间,并在C#遍历一个IEnumerable阶级差别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆