Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

linq

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.

like image 347
Shane LeBlanc Avatar asked Dec 04 '22 15:12

Shane LeBlanc


1 Answers

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>
like image 122
Not loved Avatar answered May 25 '23 00:05

Not loved