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>, .Count() will check it's underlying type and check ICollection<T>.Count. Thus it will perform roughly equivalent to calling HashSet.Count (with a slight performance hit of type casting etc).

    This is also the case for Any if running on .NET Core. But not on .NET Framework. See also CA-1860.

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

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