11

Possible Duplicate:
Which method performs better: .Any() vs .Count() > 0?

I just wonder why should I use Any() instead of Count()?, if we took the msdn example :

class Pet
{
    public string Name { get; set; }
    public int Age { get; set; }
}
class Person
{
    public string LastName { get; set; }
    public Pet[] Pets { get; set; }
}

public static void AnyEx2()
{
    List<Person> people = new List<Person>
        { new Person { LastName = "Haas",
                       Pets = new Pet[] { new Pet { Name="Barley", Age=10 },
                                          new Pet { Name="Boots", Age=14 },
                                          new Pet { Name="Whiskers", Age=6 }}},
          new Person { LastName = "Fakhouri",
                       Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}},
          new Person { LastName = "Antebi",
                       Pets = new Pet[] { }},
          new Person { LastName = "Philips",
                       Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2},
                                          new Pet { Name = "Rover", Age = 13}} }
        };

    // Determine which people have a non-empty Pet array.
    IEnumerable<string> names = from person in people
                            where person.Pets.AsQueryable().Any()
                            select person.LastName;

    foreach (string name in names)
        Console.WriteLine(name);

    /* This code produces the following output:

       Haas
       Fakhouri
       Philips
    */
}

What if I used :

  IEnumerable<string> names = from person in people
                            where person.Pets.Count() > 0
                            select person.LastName;

It will give same result ! , (I don't think it created for shortness or something) , is there any feature for Any() ??

Community
  • 1
  • 1
Mohamed Farrag
  • 1,682
  • 2
  • 19
  • 41
  • 5
    Check this post out: [Which method performs better any vs count](http://stackoverflow.com/questions/305092/which-method-performs-better-any-vs-count-0) – Mark Oreta Sep 26 '12 at 13:12
  • 14
    Someone hands you a rice-bag, and asks "are there any grains of rice?". Do you a: glance to see if there is "any" rice (at least one grain), or do you b: sit down and count them all, only reporting yes/no when you have finished? – Marc Gravell Sep 26 '12 at 13:15
  • 1
    Since it is hitting an array, "count>0" is much faster (11X in this case). I just benchmarked the above code (moving the Console.Writeline out) and "count >0" took 1400 ticks while any() took 15100 ticks! [x64,releasemode,no debugger attached]. This is because Any() has to create and destroy objects. However for a DB connection though is usually the opposite. Any() is usually performs better. – SunsetQuest Feb 19 '16 at 18:23

4 Answers4

20

Any just checks if the sequence contains at least one element, while Count needs to iterate over all elements. That's the difference. A classic scenario where Any is preferred over Count is this:

if (sec.Count() > 0)

vs

if (sec.Any())
John Washam
  • 4,073
  • 4
  • 32
  • 43
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
  • 11
    And imagine what happens if you try to `Count` an infinite sequence... – cHao Sep 26 '12 at 13:13
  • @Claudio , is it just the use of Any ? what about the overloaded ? – Mohamed Farrag Sep 26 '12 at 13:24
  • Same for the overloads, Any stops as soon as it finds the first element satisfying the predicate, while Count has to scan the whole sequence (potentially infinite, as already said). – Wasp Sep 26 '12 at 13:25
7

Depending on exactly what implementation of IEnumerable<> is hiding behind the interface, Any could potentially be vastly quicker than Count. If for example there's actually LINQ-to-SQL, or some other database provider there, it could be the difference between checking a table for at least 1 record, or having to count every record in the database.

However, to my mind, the much more important reason is that using Any() expresses your INTENT better than checking for Count() > 0. It asks "are there any items?" rather than "find out how many items there are. Is that number greater than zero". Which to you is the more natural translation of "are there any items?" ?

AakashM
  • 62,551
  • 17
  • 151
  • 186
  • I like this answer, in general you have to keep in mind that Linq might have to work with query providers, which will likely translate expressions in something else (like SQL), so expressing INTENT is important, the intent of `Any()` could correspond to physical operations that are radically different from the ones you need while doing `Count()`. – Wasp Sep 26 '12 at 13:29
2

To get the count, the code has to traverse the entire sequence. On a long, lazy-executed sequences, this can take significant time. Since I only want to know if the sequence contains one or more elements, it’s computationally more efficient to use the Any() extension method.

Read : Eric Lippert's Blog

Also userfull to read : Count() and Count property

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
2

Actually, it depends.

If your collection is in the form of an IEnumerable, the Count() method will iterate through all elements, whereas Any() won't have to. So for enumerables, Any() will have a (potentially significant) performance benefit.

In your example, however, Pets is an array, and so you would be better off using .Length rather than .Count(). In that case, there will be no significant difference of performance.

Tor Haugen
  • 19,509
  • 9
  • 45
  • 63