Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

performance of ConcurrentQueue vs Queue + lock

Tags:

c#

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.

like image 889
Oleg Vazhnev Avatar asked Jan 01 '13 14:01

Oleg Vazhnev


1 Answers

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 and Queue 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.

like image 174
Rotem Avatar answered Oct 04 '22 04:10

Rotem