ISerialized .Net, C#, Scrum and agile software development

17Sep/100

Linq performance, Count() vs Any()

I just came across some very interesting information. Every used the following statement:

if (mysequenece.Count() > 0)
{
    //Do something
}

The problem here is the Count() statement which can potentially be very inefficient, as it traverse the whole list to calculate a value. But we reallly don't need the exact count, in most cases we just need to know if there are any values, and hence, we can rather use Any() which is another extension method from Linq.

if (mysequenece.Any())
{
    //Do something
}

In the Count() example the enumeration of the source will travese the whole tree before a result is returned, in the Any() example on the other hand, the enumeration of source is stopped as soon as the result can be determined. 

Posted by Pål Eie

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

No trackbacks yet.