HastSet<T>
implements ICollection<T>
, which has a Count
property, so a call to Count()
will just call HastSet<T>.Count
, which I'm assuming is an O(1) operation (meaning it doesn't actually have to count - it just returns the current size of the HashSet
).
Any
will iterate until it finds an item that matches the condition, then stop.
So in your case, it will just iterate one item, then stop, so the difference will probably be negligible.
If you had a filter that you wanted to apply (e.g. x => x.IsValid
) then Any
would definitely be faster since Count(x => x.IsValid)
would iterate over the entire collection, while Any
would stop as soon as if finds a match.
For those reasons I generally prefer to use Any()
rather than Count()==0
since it's more direct and avoids any potential performance problems. I would only switch to Count()==0
if it provided a significant performance boost over Any()
.
Note that Any(x=>true)
is logically the same as calling Any()
. That doesn't change your question, but it looks cleaner without the lambda.