When using the extension method of IEnumerable
Count(), an array is at least two times slower than a list.
Function Co
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).