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 enumeration in
Any()stops as soon as it finds a matching item as well:https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any
I would expect the performance to be very similar. Note that the
FirstOrDefaultversion won’t work with a collection of value types (since the default isn’t null) but theAnyversion would.