I\'m currently using a List
as a queue (use lst[0]
then lst.removeAt(0)
) to hold objects. There\'s about 20 items max at a g
Short answer:
Queue
is faster than List
when it's used like a queue. List
is faster than Queue
when used like a list.
Long answer:
A Queue
is faster for dequeuing operation, which is an O(1) operation. The entire block of subsequent items of the array is not moved up. This is possible because a Queue
need not facilitate removal from random positions, but only from the top. So it maintains a head (from which the item is pulled upon Dequeue
) and tail position (to which the item is added upon Enqueue
). On the other hand removing from the top of a List
requires itself to shift positions of every subsequent item one up. This is O(n) - worst case if you're removing from the top, which is what a dequeue operation is. The speed advantage can be noticeable if you're dequeuing in a loop.
A List
is more performant if you need indexed access, random retrieval etc. A Queue
will have to enumerate fully to find the appropriate index position (it doesn't expose IList
).
That said, a Stack
vs List
is much closer, there is no performance difference in pushing and popping operations. They both push to end and remove from end of array structures (both of which are O(1)).
Of course you should use the correct structure that reveals the intent. In most cases they will perform better as well since they are tailor-made for the purpose. I believe had there been no performance difference at all, Microsoft wouldn't have included Queue
and Stack
in the framework for merely different semantics. It would have been simply easily extensible if that was the case. Think about SortedDictionary
and SortedList
, both of which do exactly the same but is differentiated by only performance characteristic; they find a place in BCL.