Shane LeBlanc
Shane LeBlanc

Reputation: 2643

FirstOrDefault(), SingleOrDefault(), Any(), etc... Which One Is The Fastest?

In regards to the above and/or including other methods, if you are searching for one record, and only one record exists, which one would perform the fastest? For example, I want to make sure that once it finds the value being queried, I'm looking for one that will return it right away without searching through the remaining records.

Upvotes: 4

Views: 8719

Answers (2)

Jim Wooley
Jim Wooley

Reputation: 10398

Single (and SingleOrDefault) should be only used when you want to force an exception if there are 0 or more than one results. The typical SQL implementation would be

Select Top 2 * from table

First on the other hand will typically short-circuit after the first match is found. In TSQL

Select Top 1 * from table

Any is used to indicate if at least one match is found (and short circuits after finding it). In TSQL, this uses the Exists.

In your case, since you need the result value, there is no use in making a separate request (with Any) and then perform Single. Instead just use FirstOrDefault and then check for null on the return result.

var foo = table.FirstOrDefault(t => t.bar == val);
if (null != foo)
   ...

Select 1 from table where Exists

Upvotes: 1

undefined
undefined

Reputation: 34248

If you have a think about this you can probably work it out.

FirstOrDefault enumerates the set until it finds a matching item

SingleOrDefault enumerates the entire collection to ensure the item occurs exactly once

This means SingleOrDefault cant be faster than FirstOrDefault. But it does depend a little on the query providers implementation

EDIT:

Any can be implemented even faster. Concider a SQL implementation:

Select Top 1 from myTable //(its not quite this but this implementation but it will be similar)

will execute faster than:

Select Top 1 from myTable where <somecondition>

Upvotes: 15

Related Questions