Performance of LINQ Any vs FirstOrDefault != null

You are mixing things here. You are talking about collections, but you don’t seem to use LINQ to objects but you are querying a database.

LINQ to objects:
Enumerable.Any and Enumerable.FirstOrDefault should perform the same, because their code is near identical:

FirstOrDefault:

foreach (TSource source1 in source)
{
    if (predicate(source1))
        return source1;
}
return default (TSource);

Any:

foreach (TSource source1 in source)
{
    if (predicate(source1))
        return true
}
return false;

LINQ to some database:
You are using Entity Framework, LINQ to SQL or NHibernate and use Queryable.Any and Queryable.FirstOrDefault on the corresponding data context.
In this case, there are really no collections, because these calls are not executed on in memory objects but translated to SQL.

This means, the performance difference stems from how the LINQ provider translates the code to SQL, so the best would be to first check the statements created. Are they equivalent? Or are they very different (select count(0) from X vs. select top 1 from X)? Then the difference might lie in the query optimizer of the DB, indexes and what not…

Leave a Comment