When I need to check whether a collection has elements or not, which of the two methods will be faster,
.Count() =! 0 or
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?
It depends on the type of enumeration.
If it is based on
.Count (property, not method) is faster because the value is already
.Count inside the structure (optimized).
.Any() requires using the sequence
In any other enumerations,
.Count() (now method) iterates over all elements.
Any() stops flowing when finding the first string, so it's faster than
Any() behaves better in most cases.