是对LINQ的计数()快于或慢于List.Count或Array.Length? [英] Is the Linq Count() faster or slower than List.Count or Array.Length?

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

问题描述

时的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.

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

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