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

后端 未结 7 970
有刺的猬
有刺的猬 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:20

    The foreach sample roughly corresponds to this code:

    using(IEnumerator e = entityList.GetEnumerator()) {
        while(e.MoveNext()) {
            Entity entity = e.Current;
            ...
        }
    }
    

    There are two costs here that a regular for loop does not have to pay:

    1. The cost of allocating the enumerator object by entityList.GetEnumerator().
    2. The cost of two virtual methods calls (MoveNext and Current) for each element of the list.

提交回复
热议问题