Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any performance difference between myCollection.Where(...).FirstOrDefault() and myCollection.FirstOrDefault(...)

Is there any performance difference between myCollection.Where(...).FirstOrDefault() and myCollection.FirstOrDefault(...)

Filling in the dots with the predicate you are using.

like image 611
Myster Avatar asked Jul 13 '09 02:07

Myster


1 Answers

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

like image 136
tnyfst Avatar answered Nov 13 '22 19:11

tnyfst