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

4.8k Views Asked by At

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
1

There are 1 best solutions below

0
On

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.