Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to add List<T> contents to ConcurrentQueue<T>

I was reading this question and noticed the OP was iterating a list to queue up items into a ConcurrentQueue.

ConcurrentQueue<TaskClass> cq = new ConcurrentQueue<TaskClass>();
for (int x = 0; x < TaskList.Count; x++)
    cq.Enqueue(TaskList[x]);

Is this necessary?

Is there a way to either:

  • Add a large number of objects to a ConcurrentQueue, or
  • Simply convert/cast a typed List into a ConcurrentQueue
like image 597
John Avatar asked Oct 18 '25 09:10

John


1 Answers

You will note that ConcurrentQueue<T> provides a constructor which accepts an IEnumerable<T> and copies its contents, like so:

ConcurrentQueue<TaskClass> queue = new ConcurrentQueue<TaskClass>(TaskList);

Why would this be faster than enqueuing each item one-by-one? Because being a constructor it is not bound by the type's thread-safety guarantee and, therefore, can get away with adding items without taking out any locks (additionally, if you look at the source you will see that Microsoft deliberately bypass some volatile field reads and writes for perf reasons).

See Reference Source for proof.

P.S. Unless you're creating large concurrent queues in a tight loop you are unlikely to observe a noticeable difference in performance, but it's worth remembering that the copy constructor is there if you need it.

like image 179
Kirill Shlenskiy Avatar answered Oct 19 '25 22:10

Kirill Shlenskiy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!