Is the LINQ Count()
method any faster or slower than List<>.Count
or Array.Length
?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Generic Generics in Managed C++
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
Marc has the right answer but the devil is in the detail.
On my machine:
IList<T>
Arrays start off slower since .Length involves only a single operation, .Count on arrays involves a layer of indirection. So .Count on arrays starts off 10x slower (on my machine), which could be one of those reasons the interface is implemented explicitly. Imagine if you had an object with two public properties, .Count and .Length. Both do the exact same thing but .Count is 10X slower.
Of course non of this really makes much of a difference since you would have to be counting your arrays and lists millions of times a second to feel a performance hit.
Code:
Results:
I believe that if you call Linq.Count() on either an ICollection or IList (like an ArrayList or List) then it will just return the Count property's value. So the performance will be about the same on plain collections.
List.Count
orArray.Length
is indeed faster than LinqCount()
. Because LinqCount()
will iterate through the whole list of items to count.List.Count
orArray.Length
use their property.In general Slower. LINQ's Count in general is an
O(N)
operation whileList.Count
andArray.Length
are both guaranteed to beO(1)
.However it some cases LINQ will special case the
IEnumerable<T>
parameter by casting to certain interface types such asIList<T>
orICollection<T>
. It will then use that Count method to do an actualCount()
operation. So it will go back down toO(1)
. But you still pay the minor overhead of the cast and interface call.I would say it depends on the List. If it is an IQueryable that is a table in a db somewhere then Count() will be much faster because it doesn't have to load all of the objects. But if the list is in-memory i would guess that the Count property would be faster if not about the same.
The
Enumerable.Count()
method checks forICollection<T>
, using.Count
- so in the case of arrays and lists, it is not much more inefficient (just an extra level of indirection).