Lists: Count vs Count ()

Given a list, which method is preferred for determining the number of elements inside?

var myList = new List<string>(); myList.Count myList.Count() 
+66
list c #
Nov 04 '10 at 15:20
source share
4 answers

Count() is an extension method introduced by LINQ, and the Count property is part of the List itself (derived from ICollection ). Internally, LINQ checks to see if it implements an IEnumerable ICollection ICollection , and if it uses this Count property. Therefore, at the end of the day, it makes no difference which one you use for List .

To prove my point, here is the code from Reflector for Enumerable.Count()

 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; } int num = 0; using (IEnumerator<TSource> enumerator = source.GetEnumerator()) { while (enumerator.MoveNext()) { num++; } } return num; } 
+81
Nov 04 '10 at 3:22 a.m.
source share

Always prefer the Count and Length properties for a type using the Count() extension method. The first is O (1) for each type that contains them. The Count() extension method has some type checking optimizations that can make it work O (1) times as well, but will degrade to O (N) if the base collection is not one of the few types that it knows about.

+17
Nov 04 '10 at 15:27
source share

myList.Count is the method in the list object, it just returns the value of the field, so very quickly. Since this is a small method, it will most likely be embedded by the compiler (or runtime), then they may allow other optimizations to be executed by the compiler.

myList.Count () calls the extension method (introduced by LINQ), which iterates over all the elements in IEnumerabl, so it should be much slower.

However (in Microsoft's implementation), the Count extension method has a β€œspecial case” for lists that allows it to use the Count count property, which means that the Count () method is only slightly slower than the Count property.

It is unlikely that you can tell the difference in speed in most applications.

So, if you know that you are dealing with a list, use the Count property, otherwise, if you have an "unknown" IEnumerabl, use the Count () method and let it optimize for you.

+8
Nov 04 '10 at 3:22 a.m.
source share

If you happen to want to change the type of your collection, you better use the Count() extension. This way you do not need to reorganize your code (e.g. use Length ).

+7
Nov 04 '10 at 15:59
source share



All Articles