哪种方法性能更好:.Any() vs .Count() >0? [英] Which method performs better: .Any() vs .Count() > 0?
问题描述
在 System.Linq
命名空间中,我们现在可以扩展我们的 IEnumerable 的 拥有Any() 和 Count() 扩展方法.
in the System.Linq
namespace, we can now extend our IEnumerable's to have the Any() and Count() extension methods.
最近有人告诉我,如果我想检查一个集合中是否包含 1 个或多个项目,我应该使用 .Any()
扩展方法而不是 .Count() >0
扩展方法,因为 .Count()
扩展方法必须遍历所有项目.
I was told recently that if i want to check that a collection contains 1 or more items inside it, I should use the .Any()
extension method instead of the .Count() > 0
extension method because the .Count()
extension method has to iterate through all the items.
其次,一些集合有一个 属性(不是扩展方法),它是 Count
或 Length
.使用它们而不是 .Any()
或 .Count()
会更好吗?
Secondly, some collections have a property (not an extension method) that is Count
or Length
. Would it be better to use those, instead of .Any()
or .Count()
?
是/否?
推荐答案
如果您从具有 .Length
或 .Count
(例如 .Length
>ICollectionIList
、List
等) - 那么这将是最快的选择,因为它没有需要经过Any()
所需的GetEnumerator()
/MoveNext()
/Dispose()
序列检查非空 IEnumerable
序列.
If you are starting with something that has a .Length
or .Count
(such as ICollection<T>
, IList<T>
, List<T>
, etc) - then this will be the fastest option, since it doesn't need to go through the GetEnumerator()
/MoveNext()
/Dispose()
sequence required by Any()
to check for a non-empty IEnumerable<T>
sequence.
对于IEnumerable
,Any()
通常会更快,因为它只需要查看一次迭代.但是,请注意 Count()
的 LINQ-to-Objects 实现确实会检查 ICollection
(使用 .Count
作为优化) - 因此,如果您的基础数据源直接是一个列表/集合,则不会有很大的不同.不要问我为什么不使用非通用的 ICollection
...
For just IEnumerable<T>
, then Any()
will generally be quicker, as it only has to look at one iteration. However, note that the LINQ-to-Objects implementation of Count()
does check for ICollection<T>
(using .Count
as an optimisation) - so if your underlying data-source is directly a list/collection, there won't be a huge difference. Don't ask me why it doesn't use the non-generic ICollection
...
当然,如果您使用 LINQ 对其进行过滤等(Where
等),您将拥有一个基于迭代器块的序列,因此这个 ICollection
优化没用.
Of course, if you have used LINQ to filter it etc (Where
etc), you will have an iterator-block based sequence, and so this ICollection<T>
optimisation is useless.
通常使用 IEnumerable
:坚持使用 Any()
;-p
In general with IEnumerable<T>
: stick with Any()
;-p
这篇关于哪种方法性能更好:.Any() vs .Count() >0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!