Possible Duplicate:
LINQ extension methods – Any() vs. Where() vs. Exists()
Given a list of objects in memory I ran the following two expressions:
myList.where(x => x.Name == "bla").Any()
vs
myList.Any(x => x.Name == "bla")
The latter was fastest always, I believe this is due to the Where enumerating all items. But this also happens when there’s no matches.
Im not sure of the exact WHY though. Are there any cases where this viewed performance difference wouldn’t be the case, like if it was querying Nhib?
Cheers.
The
Any()with the predicate can perform its task without an iterator (yield return). Using aWhere()creates an iterator, which adds has a performance impact (albeit very small).Thus, performance-wise (by a bit), you’re better off using the form of
Any()that takes the predicate (x => x.Name == "bla"). Which, personally, I find more readable as well…On a side note,
Where()does not necessarily enumerate over all elements, it just creates an iterator that will travel over the elements as they are requested, thus the call toAny()after theWhere()will drive the iteration, which will stop at the first item it finds that matches the condition.So the performance difference is not that
Where()iterates over all the items (in linq-to-objects) because it really doesn’t need to (unless, of course, it doesn’t find one that satisfies it), it’s that theWhere()clause has to set up an iterator to walk over the elements, whereasAny()with a predicate does not.