Question:
When I need to check whether a collection has elements or not, which of the two methods will be faster, .Count() =! 0
or .Any()
?
I've heard that .Count()
can be faster in some cases. But checking the source code , the Any()
method seemed better to use.
There is also the possibility of having a condition inside the method, in which case you can change which of the two is faster?
And when it is used in a DbSet
, the query generated by .Any()
is different from .Count()
I imagine. But when it comes to performance, is Any()
still ahead?
Answer:
It depends on the type of enumeration.
If it is based on ICollection<T>
, .Count
(property, not method) is faster because the value is already .Count
inside the structure (optimized)..Any()
requires using the sequence GetEnumerator()
/ MoveNext()
/ Dispose()
.
In any other enumerations,.Count()
(now method) iterates over all elements. Any()
stops flowing when finding the first string, so it's faster than .Count()
In summary, Any()
behaves better in most cases.