FirstOrDefault(), SingleOrDefault(), Any(), etc... Which One Is The Fastest?
.net, linq
Solution
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>
Problem
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.