时的LINQ的计数(
)的方法比任何名单,其中更快或更慢;> .Count之间
或 Array.Length
?
Is the Linq Count(
) method any faster or slower than List<>.Count
or Array.Length
?
在一般的慢。 LINQ的计数一般是 O(N)
操作,而 List.Count
和阵列。长度
都保证是 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将特殊情况下,的IEnumerable&LT; T&GT; T&GT;
通过转换成特定的接口类型,如的IList&LT参数
或的ICollection&LT; T&GT;
。然后,将使用该计数方法做一个实际的计数()
操作。因此,将回落到 0去(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.