Array.Count() much slower than List.Count()

前端 未结 4 1873
梦如初夏
梦如初夏 2021-02-01 18:00

When using the extension method of IEnumerable Count(), an array is at least two times slower than a list.

Function                      Co         


        
4条回答
  •  梦毁少年i
    2021-02-01 18:27

    The reason is that Enumerable.Count() performs a cast to ICollection to retrieve the count both from the list and the array.

    Using this sample code:

    public static int Count(IEnumerable source)
    {
        ICollection collection = source as ICollection;
        if (collection != null)
        {
            return 1; // collection.Count;
        }
    }
    

    you can determine that the cast takes much longer for the array, in fact most of the time taken for counting is from this cast:

    Function                      Count()
    List                     1,575
    int[]                         5,069
    

    The key might be this statement from the documentation (emphasis mine):

    In the .NET Framework version 2.0, the Array class implements the System.Collections.Generic.IList, System.Collections.Generic.ICollection, and System.Collections.Generic.IEnumerable generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations).

提交回复
热议问题