LINQ Any 与 FirstOrDefault 的性能 != null [英] Performance of LINQ Any vs FirstOrDefault != null
问题描述
在我贡献的开源项目 (OSP) 代码中有多个地方,必须确定集合中的元素是否满足特定条件.
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.
我见过在某些情况下使用 LINQ 表达式 Any(lambda expression)
和在其他情况下使用 FirstOrDefault(lambda expression) != null
但从未考虑过关于它.
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.
所以我认为 FirstOrDefault(lambda expression) != null
应该比 Any(lambda expression)
快,对吧?
So I figured that FirstOrDefault(lambda expression) != null
should be faster than Any(lambda expression)
,right?
在 FirstOrDefault(lambda expression) != null
的情况下,迭代(可能)在找到满足条件的元素时停止(更坏的情况是它遍历整个集合并返回null
).
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
).
在 Any(lambda 表达式)
的情况下,我想即使找到满足条件的元素,迭代也会继续到集合的末尾.
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.
上述内容不正确,因为 Jackson Pope 提到并链接了相关的 MSDN 文章.
The above is not true as Jackson Pope mentioned and linked the related MSDN article.
我的想法是正确的还是遗漏了什么?
Are my thoughts correct or am I missing something?
推荐答案
Any()
中的枚举也会在找到匹配项后立即停止:
The enumeration in Any()
stops as soon as it finds a matching item as well:
https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any
我希望性能非常相似.请注意,FirstOrDefault
版本不适用于值类型的集合(因为默认值不是 null),但 Any
版本可以.
I would expect the performance to be very similar. Note that the FirstOrDefault
version won't work with a collection of value types (since the default isn't null) but the Any
version would.
这篇关于LINQ Any 与 FirstOrDefault 的性能 != null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!