You will have to benchmark them, because the Any()
is something like
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
if (enumerator.MoveNext())
{
return true;
}
}
return false;
so it requires enumeration, that for ConcurrentDictionary
is something complex, but even the Count
of ConcurrentDictionary
isn't cached and it seems to be pretty complex.
I'll add that the Count
must still traverse some internal structures (as in an array of) aquiring a lock on the whole dictionary, while the Any()
will stop at the first non-empty bucket. I'll say that for a big dictionary, Count
is slower, while for a small one it is faster.
Correction: the Count
aquires a lock on all the dictionary before counting. it does call this.AcquireAllLocks()
.
Remember that the result of both method could be falsified before the methods return, because hey... concurrency! :-)