Enumerating via interface - performance loss

后端 未结 4 908
情书的邮戳
情书的邮戳 2021-02-13 11:57

I had a little dispute (which was very close to holy war:) ) with my colleage, about the performance of access to list via indeces VS via enumerator. To operat

4条回答
  •  暖寄归人
    2021-02-13 12:38

    When using List, the foreach doesn't actually use the IEnumerable interface; rather, it uses List.Enumerator, which is a struct. At the trivial level, this means slightly less indirection - not having to de-reference, and using static calls rather than virtual calls - and a more direct implementation.

    These differences are very very small, and in any sensible real-life example the difference is noise. However, it may be marginally noticeable if testing just the foreach performance.

    To expand on this: foreach doesn't actually require IEnumerable[] - it can work purely on the GetEnumerator() / .MoveNext() / .Current / .Dispose() pattern; this was especially important before generics in 2.0.

    However, this is only possible when the variable is typed as List (which has a custom GetEnumerator() method). Once you have IEnumerable, it has to use IEnumerator

提交回复
热议问题