Is there any performance difference between myCollection.Where(...).FirstOrDefault() and myCollection.FirstOrDefault(...)
Filling in the dots with the predicate you are using.
Is there any performance difference between myCollection.Where(...).FirstOrDefault() and myCollection.FirstOrDefault(...)
Filling in the dots with the predicate you are using.
Assuming we're talking LinqToObjects (obviously LinqToSql, LinqToWhatever have their own rules), the first will be ever so slightly slower since a new iterator must be created, but it's incredibly unlikely that you would ever notice the difference. In terms of number of comparisons and number of items examined, the time the two take to run will be virtually identical.
In case you're worried, what will not happen is that the .Where operator filters the list to n items and the .FirstOfDefault takes the first out of the filtered list. Both sequences will short-circuit correctly
If we assume that in both cases you're using the Extension methods provided by the Enumerable
static class, then you'll be hard pressed to measure any difference between the two.
The longer form ...
myCollection.Where(...).FirstOrDefault()
... will (technically) produce more memory activity (creating an intermediary iterator to handle the Where()
clause) and involve a few more cycles of processing.
The thing is that these iterators are lazy - the Where()
clause won't go merrily through the entire list evaluating the predicate, it will only check as many items as necessary to find one to pass through.