Is the Linq Count() faster or slower than List.Count or Array.Length?

前端 未结 7 550
你的背包
你的背包 2020-11-29 04:59

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

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 05:40

    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).

    However it some cases LINQ will special case the IEnumerable parameter by casting to certain interface types such as IList or ICollection. 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.

提交回复
热议问题