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

后端 未结 7 857
有刺的猬
有刺的猬 2020-12-17 17:00

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

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

and <

7条回答
  •  有刺的猬
    2020-12-17 17:17

    One point missed here: A List has a Count property, it internally keeps track of how many elements are in it.

    An IEnumerable DOES NOT.

    If you program to the interface IEnumerable and use the count extention method it will enumerate just to count the elements.

    A moot point though since in the IEnumerable you cannot refer to items by index.

    So if you want to lock in to Lists and Arrays you can get small performance increases.

    If you want flexability use foreach and program to IEnumerable. (allowing the use of linq and/or yield return).

提交回复
热议问题