There are multiple places in an Open Source Project (OSP) code I contribute, where it has to be determined if an element in a collection satisfies a certain condition.
I've seen the use of LINQ expression Any(lambda expression)
in some cases and FirstOrDefault(lambda expression) != null
in others but never given a thought about it.
I have reached now a point where I have to do some iterations to collections made from queries to a DB and want to optimize the runtime.
So I figured that FirstOrDefault(lambda expression) != null
should be faster than Any(lambda expression)
,right?
In the case of FirstOrDefault(lambda expression) != null
, the iteration (probably) stops when it finds an element that satisfies the condition (worse case scenario it iterates through the entire collection and returns null
).
In the case of Any(lambda expression)
I imagine that the iteration continues to the end of the collection even if an element that satisfies the condition is found.
Edit: The above is not true as Jackson Pope mentioned and linked the related MSDN article.
Are my thoughts correct or am I missing something?
The . Any implementation should be the fastest one.
We use Redgate's Performance profiler to find some performance leaks. Our tool uses Linq to objects in several methods. But we have noticed that a FirstOrDefault takes very long on collections with +/- 1000 objects. The profiler also alerts that the query is very slow.
c# - FirstOrDefault is signicantly faster than SingleOrDefault while viewing ANTS profiler - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
You are mixing things here. You are talking about collections, but you don't seem to use LINQ to objects but you are querying a database.
LINQ to objects:Enumerable.Any
and Enumerable.FirstOrDefault
should perform the same, because their code is near identical:
FirstOrDefault
:
foreach (TSource source1 in source) { if (predicate(source1)) return source1; } return default (TSource);
Any
:
foreach (TSource source1 in source) { if (predicate(source1)) return true } return false;
LINQ to some database:
You are using Entity Framework, LINQ to SQL or NHibernate and use Queryable.Any
and Queryable.FirstOrDefault
on the corresponding data context.
In this case, there are really no collections, because these calls are not executed on in memory objects but translated to SQL.
This means, the performance difference stems from how the LINQ provider translates the code to SQL, so the best would be to first check the statements created. Are they equivalent? Or are they very different (select count(0) from X
vs. select top 1 from X
)? Then the difference might lie in the query optimizer of the DB, indexes and what not...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With