Linq Count() 比 List.Count 或 Array.Length 快还是慢? [英] Is the Linq Count() faster or slower than List.Count or Array.Length?
问题描述
LINQ Count()
方法是否比 List<>.Count
或 Array.Length
更快或更慢?
Is the LINQ Count()
method any faster or slower than List<>.Count
or Array.Length
?
推荐答案
总的来说比较慢.LINQ 的 Count 通常是 O(N)
操作,而 List.Count
和 Array.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 会通过转换为某些接口类型(例如 IList
或 ICollection
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屋!