performance of ConcurrentQueue vs Queue + lock
I have to implement one-consumer one-producer standard algorithm. I can implement it using Queue
and couple of lock
statements easily. Or I can just use ConcurrentQueue
. What is better?
If Queue + lock
is used then I can optimize "multiple addition/retreival", because I can lock
once and then Add
many times.
What is faster in general case - ConcurrentQueue
or Queue + lock
and how much the difference is? Of course ConcurrentQueue
is the most straigt forward way but I do not want to loose a lot of performance as I'm using this in HFT trading application.
Solution 1:
From C# in a Nutshell:
The concurrent stack, queue, and bag classes are implemented internally with linked lists. This makes them less memory efficient than the nonconcurrent
Stack
andQueue
classes, but better for concurrent access because linked lists are conductive to lock-free or low-lock implementations.
In other words, it's hard to define a general case, not to mention predict what the difference in performance will be.
It depends on the size of the collection and the usage. Performance can be expected to be better given enough concurrent access, memory consumption will be worse.