Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between foreach and for loops over an IEnumerable class in C#

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

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

and

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

where

List<Entity> entityList;

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?

like image 810
Craig Avatar asked Sep 04 '08 17:09

Craig


1 Answers

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.

like image 93
Daniel Jennings Avatar answered Sep 19 '22 14:09

Daniel Jennings