Lists: Count vs Count() [duplicate]
Asked Answered
K

4

142

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

var myList = new List<string>();

myList.Count
myList.Count()
Khmer answered 4/11, 2010 at 15:20 Comment(5)
@Randy: Depending on the type of the variable it's preferable to use 'var' instead of 'Dictionary<List<string>,int>'. It's a matter of preference.Spectrograph
@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!).Hotfoot
@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 …Castroprauxel
@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 :)Khmer
https://mcmap.net/q/119654/-resharper-and-var-duplicate/8796643Zygote
B
155

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;
}
Bingle answered 4/11, 2010 at 15:22 Comment(7)
"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 ;)Granado
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.Robyn
@BFree, How we can call this in VB.NET ?Giraldo
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.Slily
Source can be found here - github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/…Dennet
@bfree any idea why there is no array check in order to get Length prop instead?Inanimate
@Inanimate 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: github.com/dotnet/corefx/blob/master/src/System.Linq/src/System/… Arrays implement ICollection, so Arrays will get picked up by this as well.Bingle
E
42

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.

Enrobe answered 4/11, 2010 at 15:27 Comment(4)
FYI: If you're checking to see if anything exists, use the Any() extension method.Eskimoaleut
@Eskimoaleut I would prefer Count > 0 over Any().Longueur
In OP's example (using a List<T>), definitely use Count>0. If you're using IEnumerable<T> then Any() is preferred in most cases, unless the underlying source itself is likely to be List<T>.Tonisha
There's an interesting post about what's the most efficient in the different use cases : #18652440Discography
L
14

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.

Lawanda answered 4/11, 2010 at 15:22 Comment(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.Bingle
can you elaborate? What do you mean by built in?Spectrograph
H
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).

Hedgcock answered 4/11, 2010 at 15:59 Comment(1)
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.)Definitive

© 2022 - 2024 — McMap. All rights reserved.