Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

linq

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

like image 725
NotDan Avatar asked Jun 11 '09 14:06

NotDan


2 Answers

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

like image 146
JaredPar Avatar answered Sep 23 '22 01:09

JaredPar


The Enumerable.Count() method checks for ICollection<T>, using .Count - so in the case of arrays and lists, it is not much more inefficient (just an extra level of indirection).

like image 24
Marc Gravell Avatar answered Sep 19 '22 01:09

Marc Gravell