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

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

Fill points with the predicate you use.

+6
performance linq
source share
2 answers

Assuming we're talking about LinqToObjects (obviously LinqToSql, LinqToWhatever have their own rules), the former will be so slightly slower since a new iterator needs to be created, but it is incredibly unlikely that you will notice the difference. As for the number of comparisons and the number of items examined, the time during which they will be performed will be almost identical.

If you are worried that this will not happen, the .Where statement will filter the list by n items, and .FirstOfDefault will select the first one from the filtered list. Both sequences will be shorted correctly.

+6
source share

Assuming that in both cases you are using extension methods provided by the static Enumerable class, then it will be difficult for you to measure the difference between them.

Longer shape ...

 myCollection.Where(...).FirstOrDefault() 

... will (technically) produce more memory activity (creating an intermediate iterator to process the Where() clause) and engage a few more processing cycles.

The fact is that these iterators are lazy - the Where() sentence will not go through the entire list evaluating the predicate, it will only check as many elements as necessary to find them to pass through.

0
source share

All Articles