Search code examples
c#.netperformancehashset

Empty HashSet - Count vs Any


I am only interested to know whether a HashSet hs is empty or not. I am NOT interested to know exactly how many elements it contains.

So I could use this:

bool isEmpty = (hs.Count == 0);

...or this:

bool isEmpty = hs.Any(x=>true);

Which one provides better results, performance-wise(specially when the HashSet contains a large number of elements) ?


Solution

  • Since HashSet<T> implements ICollection<T>, both .Count() and .Any() will check it's underlying type and check ICollection<T>.Count. Thus they will perform roughly equivalent to calling HashSet.Count (with a slight performance hit of type casting etc).

    You definitely should not call hs.Any(x=>true); though - since that Any method (taking the predicate) will not take advantage of the ICollection<T>.Count optimisation.

    Source: .NET Core Runtime, .NET Core Runtime, .NET Core Runtime