public class Group
{
public string Name { get; set; }
}
Test:
List _groups = new List();
for (i
Following on from Matthew Watson's answer:
The reason iterating over a List
generates call
instructions rather than callvirt
, as used for IEnumerable
, is that the C# foreach
statement is duck-typed.
The C# Language Specification, section 8.8.4, says that the compiler 'determines whether the type X has an appropriate GetEnumerator method'. This is used in preference to an enumerable interface. Therefore the foreach
statement here uses the overload of List
which returns a List
rather than the version that returns IEnumerable
or just IEnumerable
.
The compiler also checks that the type returned by GetEnumerator
has a Current
property and a MoveNext
method that takes no arguments. For List
, these methods are not marked virtual
, so the compiler can compile a direct call. In contrast, in IEnumerator
they are virtual
so the compiler must generate a callvirt
instruction. The extra overhead of calling through the virtual function table explains the difference in performance.