Linq Count() 比 List.Count 或 Array.Length 快还是慢? [英] Is the Linq Count() faster or slower than List.Count or Array.Length?

查看:30
本文介绍了Linq Count() 比 List.Count 或 Array.Length 快还是慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

LINQ Count() 方法是否比 List<>.CountArray.Length 更快或更慢?

Is the LINQ Count() method any faster or slower than List<>.Count or Array.Length?

推荐答案

总的来说比较慢.LINQ 的 Count 通常是 O(N) 操作,而 List.CountArray.Length 都保证是 O(1).

In general Slower. LINQ's Count in general is an O(N) operation while List.Count and Array.Length are both guaranteed to be O(1).

但是,在某些情况下,LINQ 会通过转换为某些接口类型(例如 IListICollection)来对 IEnumerable 参数进行特殊处理;.然后它将使用该 Count 方法进行实际的 Count() 操作.所以它会回到O(1).但是您仍然需要支付转换和接口调用的少量开销.

However it some cases LINQ will special case the IEnumerable<T> parameter by casting to certain interface types such as IList<T> or ICollection<T>. It will then use that Count method to do an actual Count() operation. So it will go back down to O(1). But you still pay the minor overhead of the cast and interface call.

这篇关于Linq Count() 比 List.Count 或 Array.Length 快还是慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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