140

Given a list, which method is preferred to determine the number of elements inside?

var myList = new List<string>();

myList.Count
myList.Count()
Venkat
  • 2,549
  • 2
  • 28
  • 61
Saxman
  • 5,009
  • 11
  • 51
  • 72
  • 3
    @Randy: Depending on the type of the variable it's preferable to use 'var' instead of 'Dictionary,int>'. It's a matter of preference. –  Nov 04 '10 at 15:24
  • @Randy: Not sure that's relevant to the question; it's a stylistic choice (one I also happen to disagree with, but that discussion is for a different thread!). – Dan Puzey Nov 04 '10 at 15:26
  • @Randy: why not? The compiler knows the type, why should I need to write it? Furthermore, *do* you know the type? What is it? `int`? `long`? Does it matter? Certainly not for this code, or for most code … – Konrad Rudolph Nov 04 '10 at 16:01
  • @Randy - As many has said, it's a matter of preferences, and for cases where I don't really know the type, and it's faster :) – Saxman Nov 04 '10 at 18:00
  • http://stackoverflow.com/questions/737835/resharper-and-var/8796643 – jedmao Jan 09 '12 at 23:26

4 Answers4

153

Count() is an extension method introduced by LINQ while the Count property is part of the List itself (derived from ICollection). Internally though, LINQ checks if your IEnumerable implements ICollection and if it does it uses the Count property. So at the end of the day, there's no difference which one you use for a List.

To prove my point further, here's 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;
}
BFree
  • 102,548
  • 21
  • 159
  • 201
  • 37
    `"So at the end of the day, there's no difference ..."` Apart from the fact that LINQ needed the day to decide that it uses the builtin function ;) – Tim Schmelter Nov 04 '10 at 15:28
  • 15
    There is a small difference. LINQ has to check to see if it implements ICollection...so there is a small (probably not even noticeable) hit to make this check. – Dismissile Nov 04 '10 at 15:33
  • @BFree, How we can call this in VB.NET ? – kbvishnu Nov 15 '13 at 10:57
  • 12
    from a maintenance perspective, I'd recommend using `Count()` in case your type changes from a `List` to some other `IEnumerable` that doesn't have a `Count` property. – DLeh Dec 10 '15 at 18:30
  • Source can be found here - https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/Count.cs#L19 – Kevin Smith Sep 08 '17 at 17:08
  • @bfree any idea why there is no array check in order to get Length prop instead? – juanora Oct 26 '21 at 11:56
  • 2
    @juanora This answer is from 11 years ago, so I can't answer for back then. These days however, there's another check in there for the non generic ICollection in which case it returns Count. See here: https://github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/Linq/Count.cs#L29 Arrays implement ICollection, so Arrays will get picked up by this as well. – BFree Oct 26 '21 at 18:27
41

Always prefer Count and Length properties on a type over the extension method Count(). The former is an O(1) for every type which contains them. The Count() extension method has some type check optimizations that can cause it to run also in O(1) time but will degrade to O(N) if the underlying collection is not one of the few types it knows about.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 14
    FYI: If you're checking to see if anything exists, use the `Any()` extension method. – Greg Nov 04 '10 at 16:03
  • 4
    @Greg I would prefer `Count > 0` over `Any()`. – Rudey Feb 18 '16 at 11:42
  • 1
    In OP's example (using a List), definitely use Count>0. If you're using IEnumerable then Any() is preferred in most cases, unless the underlying source itself is likely to be List. – Liam Laverty Nov 07 '16 at 16:35
13

myList.Count is a method on the list object, it just returns the value of a field so is very fast. As it is a small method it is very likely to be inlined by the compiler (or runtime), they may then allow other optimization to be done by the compiler.

myList.Count() is calling an extension method (introduced by LINQ) that loops over all the items in an IEnumerable, so should be a lot slower.

However (In the Microsoft implementation) the Count extension method has a “special case” for Lists that allows it to use the list’s Count property, this means the Count() method is only a little slower than the Count property.

It is unlikely you will be able to tell the difference in speed in most applications.

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

AGuyCalledGerald
  • 7,882
  • 17
  • 73
  • 120
Ian Ringrose
  • 51,220
  • 55
  • 213
  • 317
  • 2
    That's not accurate. If you look at the implementation for the Count() method, it checks to see if the IEnumerable implements ICollection, and if it does it uses the Count property. So they're both the same at the end of the day. – BFree Nov 04 '10 at 15:24
  • can you elaborate? What do you mean by built in? –  Nov 04 '10 at 15:25
7

If you by any chance wants to change the type of your collection you are better served with the Count() extension. This way you don't have to refactor your code (to use Length for instance).

Simon Fischer
  • 3,816
  • 3
  • 23
  • 32
  • using `Count()` gives you 1 less than thing to worry about changing if you decide to use a different type of collection (in that `.Count()` will work if it's an Array, a List, etc.) – Don Cheadle Jul 13 '16 at 18:35