LINQ performance Count vs Where and Count

前端 未结 6 2001
礼貌的吻别
礼貌的吻别 2020-12-08 10:14
public class Group
{
   public string Name { get; set; }
}  

Test:

List _groups = new List();

for (i         


        
6条回答
  •  一整个雨季
    2020-12-08 10:27

    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.GetEnumerator which returns a List.Enumerator 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.Enumerator, 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.

提交回复
热议问题