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
When using List
, the foreach
doesn't actually use the IEnumerable
interface; rather, it uses List
, 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