I am using push_front()
and push_back()
only. Thus, I do not incur any other cost of using insert()
or remove()
.
I know both containers offer O(1)
complexity for each of these functions, deque
s having amortized constant time compared to list
s having constant time.
But I want to know which time is less than the other, if there is, at all.
In the case of random insert, in theory, the list should be much faster, its insert operation being in O(1) versus O(n) for a vector or a deque. The container is filled with all the numbers in [0, N] and shuffled. Then, 1000 random values are inserted at a random position in the container.
A deque is a set of linked memory blocks, where more than one element is stored in each memory block. A list is a set of elements dispersed in memory, i.e.: only one element is stored per memory "block".
Deque has some advantages associated with respect to good performance, especially for insertion and deletion at the front, whereas on the other hand, we have a vector that has some repercussions like bad performance for performing insertion and deletion from one end.
Consider using std::list if: You need to store many items but the number is unknown. You need to insert or remove new elements from any position in the sequence. You do not need efficient access to random elements.
Not sure how to answer your question. You seem to want us to write a benchmark program that you could easily write yourself. So instead of doing that, I'll just state this:
list
, every item you push will incur a memory allocation.deque
, large blocks are allocated at once.Given that memory allocation is normally slow, I would expect the deque
to out-perform list.
If you push or pop many items at once, this will be especially true, as cache locality comes into play.
Of course, you could write an allocator on the list to use a memory pool. Then you might get better performance.
So with these hypotheses in mind, go away and measure it, and if you want to discuss the results, that would be the time to ask a question.
Whenever it comes to performance, it's a bad idea to "guess" (or ask on the internet, which is slightly better than guessing, but only somewhat), and always best to measure the two options - in this case, just do a loop, and push_back or push_front enough things to make it realistic [you may want to make it more realistic and run most of what your code does, and do that in a loop enough times to make it last enough to measure the time - it's often more realistict than adding a bazillion values to a list
/deque
and then finding that "when you have to swap out, it gets very slow!"].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With