Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance difference between .where(...).Any() vs ..Any(...) [duplicate]

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.

like image 734
clonesegg Avatar asked May 29 '12 13:05

clonesegg


People also ask

Is find faster than FirstOrDefault?

Find() runs almost as twice as faster, hoping . Net team will not mark it Obsolete in the future. Try timing Find() before FirstOrDefault . What are the results then?

What is any () in C#?

The Any method checks whether any of the element in a sequence satisfy a specific condition or not. If any element satisfy the condition, true is returned.

What is Linq in C# with example?

LINQ is the basic C#. It is utilized to recover information from various kinds of sources, for example, XML, docs, collections, ADO.Net DataSet, Web Service, MS SQL Server, and different database servers.

What is all in Linq C#?

The Linq All Operator in C# is used to check whether all the elements of a data source satisfy a given condition or not. If all the elements satisfy the condition, then it returns true else return false. There is no overloaded version is available for the All method.


1 Answers

The Any() with the predicate can perform its task without an iterator (yield return). Using a Where() 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 to Any() after the Where() 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 the Where() clause has to set up an iterator to walk over the elements, whereas Any() with a predicate does not.

like image 166
James Michael Hare Avatar answered Sep 23 '22 02:09

James Michael Hare