tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Count for System.Collections.Concurrent.ConcurrentStack<T>

17 Apr 2012 1 mins .NET, Best practice or not?, Multithreading/Parallelism/Asynchronous/Concurrency

Collections in System.Collections.Concurrent namespace are optimized for access from more (basically) threads. That means no stupid “one-lock-for-everything” approach. Actually these are lock free.

It’s good for performance, but also, if used foolhardily, the performance penalty can be too big. One example can be the ConcurrentStack<T> class. As with a lot of collections, this stack also has a Count property. But because it’s a lock free implementation using linked list the Count isn’t that easy. Actually it’s O(n) and this can be especially bad for big stacks. So use with care. As the remarks for this property recommends, if you need to know just whether it’s empty of not, the IsEmpty is better (though realize, that in time you check it it might be empty, but not on next line where you’re about to perform some action and vice versa).

Use the tools, but also know your tools.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at