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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…