Is there any difference between Count () (linq extension) and List <T> .Count
List<string> list = new List<string>() {"a", "b", "c"}; IEnumerable<string> enumerable = list; int c1 = list.Count; int c2 = list.Count(); int c3 = enumerable.Count(); Are there differences in performance and implementation between these last 3 statements? Will list.Count() work worse or the same as list.Count , and it matters if the link is of type IEnumerable<string> ?
Take a look at Reflector:
public static int Count<TSource>(this IEnumerable<TSource> source) { if (source == null) { throw Error.ArgumentNull("source"); } ICollection<TSource> is2 = source as ICollection<TSource>; if (is2 != null) { return is2.Count; } ICollection is3 = source as ICollection; if (is3 != null) { return is3.Count; } int num = 0; using (IEnumerator<TSource> enumerator = source.GetEnumerator()) { while (enumerator.MoveNext()) { num++; } } return num; } So, if your IEnumerable<T> implements ICollection<T> or ICollection , it will return the Count property.
The Linq Count method is smart enough not to iterate over the base collection if it implements the ICollection interface and therefore already has the Count property.
Performing a count on IEnumerable first checks to see if the enumerated list implements ICollection<T> , where T is the general parameter of the enumerated list.
If so, it returns an ICollection<T>.Count .
If not, it checks to see if it implements ICollection . If it returns, it returns ICollection.Count .
If he does not implement any of them, he must iterate over the whole list and count, and this can be an expensive operation for a large list.
List<string> however implements ICollection<string> , and therefore the performance will be the same.
I assume that it works as follows: List stores its own score in a variable. Count () iterates through IEnumerable to count the number of elements. This would make List.Count more efficient.