哪种方法效果更好:。任何()与.Count之间()> 0? [英] Which method performs better: .Any() vs .Count() > 0?

查看:133
本文介绍了哪种方法效果更好:。任何()与.Count之间()> 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.Linq的命名空间,我们现在可以扩展我们的的IEnumerable 的有任何()计数()扩展方法的。

in the System.Linq namespace, we can now extend our IEnumerable's to have theAny() and Count() extension methods.

我最近告知,如果我要检查,一个集合包含1个或多个项目里面,我应该使用的的。任何()扩展方法,而不是 .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之间()

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() ?

啊/ NAE?

推荐答案

如果你开始的东西,有一个 .Length .Count之间(如的ICollection< T> 的IList< T> 列表< T> 等) - 那么这将是最快的选项,因为它并不需要经过的的GetEnumerator() / 的MoveNext() / 的Dispose()要求任何()来检查是否有非空的的IEnumerable< T>

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&LT; T&GT; ,然后任何()一般的是更快,因为它只有多看一眼迭代。但是,请注意,LINQ到对象实施伯爵()不检查的ICollection&LT; T&GT; (使用 .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对其进行过滤等(其中,等),你将有一个迭代器基于块的序列,因此该的ICollection&LT; T&GT; 的优化是没有用的。

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&LT; T&GT; :坚持使用任何() ;-p

In general with IEnumerable<T> : stick with Any() ;-p

这篇关于哪种方法效果更好:。任何()与.Count之间()&GT; 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆