std::deque, almost always the wrong choice
07 Feb 2026 - John Z. Li
This post argues that std::deque and std::queue (an adapter class of the former)
are almost always the wrong choice in C++ programming.
How does std::deque work?
From the perspective of data structure,
a std::deque is basically an array of pointers to a set of fixed-sized chunks of memory.
The chunk size is a hard-coded compile-time constant and is implementation defined.
Take GCC’s standard library implementation libstdc++ as an example, for type of small sizes,
a chunk size of 512 bytes is used.
Take std::deque<double> as an example. Starting from an empty queue:
- The size of
doubleis8bytes, which means a chunk can hold64elements. - When a
doubleis pushed into the queue, a chunk of512bytes of memory is allocated. - The
doubleis put at the beginning of the chunk. - A pointer pointing to the chunk is pushed into the pointer array
// dequeue size is 1 |pointer array| |begin |end |pointer[0] |--------> Chunk_0 (double, [empty], ...)
Another 63 elements can be pushed into the queue without triggering memory allocation.
After 64 elements have been in the queue, pushing another 65-th
element will trigger allocation of a new chunk:
// queue size is 65
|pointer array | |beggin
|pointer[0] |--------> Chunk_0 (double[64])
|pointer[1] |--------> Chunk_1 (double, [empty], ...)
|end
Popping one element from front deconstructs the first element in first chunk and
increases an internal begin offset:
// queue size is 64
|pointer array | |beggin
|pointer[0] |--------> Chunk_0 ([empty], double[63])
|pointer[1] |--------> Chunk_1 (double, [empty], ...)
|end
It is only when all the first 64 elements are popped, the first chunk is freed:
// queue size if 1
|pointer array |
|pointer[0] |--------> NULL (Chunk_0 is freed)
|pointer[1] |--------> Chunk_1 (double, [empty], ...)
|begin |end
Pushing another 64 elements into the back of the queue will be either like this
// pointer array reallocated or rotated, iterators to existing elements invalidated
// pointer[0] is previously pointer[1]
// dequeue size if 65
|Array of pointer| |begin
|pointer[0] |--------> Chunk_1 (double[64])
|pointer[1] |--------> Chunk_2 (double, empty, ...)
|end
or like this:
// pointer array not reallocated nor rotated, iterators to existing elements still valid
// queue size if 65
|Array of pointer|
|pointer[0] |--------> NULL (Chunk_0 is freed)
|begin
|pointer[1] |--------> Chunk_1 (double[64])
|pointer[2] |--------> Chunk_2 (double, empty, ...)
|end
In practice, this means you need to assume that any push_back or push_front
will invalidate iterators to stay safe.
The iterator for std::deque typically contains 4 elements:
node, a pointer pointing to an element in the pointer array.first, a pointer pointing to the begin of the chunk.last, a pointer pointing to one-past-the-end of the current memory chunk.current, a pointer to the current element.
For an iterator i, ++i first checks whether ++current == last. If no, then
++current already points to the next element. Otherwise, update node to ++node,
and update first/last to the begin/end of the chunk pointed by updated *node respectively,
and current to the value of updated first.
--i is similar, but current is compared with first for boundary check.
Random access is done using modular arithmetic. For an iterator i, i + n is computed
by taking into account of the fact that a chunk only contains a fixed number of elements.
node = node + (current - frst + n) / Number_of_elements_per_chunk;
current = *node + (current - first + n) % Number_of_elements_per_chunk;
frst = *node;
last = first + Number_of_elements_per_chunk;
We can see the fixed chunk size serves two purposes at the same time: to make random access possible and reduce memory allocation cost by allocating a big chunk at a time. A typical optimization employed by many implementations is to keep one chunk when the queue is popped empty, so that a operation sequence like below would not trigger repetitive allocation and deallocation.
push one; pop one; push one; pop one, ...
Why you probably should not use std::deque
std::deque uses a clever trick to reduce memory allocation cost,
while keeping iterators random accessible and stable under popping from both ends.
All of these are nice at first glance, but not so much under closer inspection.
In C++, with modern malloc implementations such as jemalloc or tcmalloc,
each thread often has its own per-thread memory pool or arena. Allocation of a small
pieces of memory can often be satisfied very fast.
This is not to say that allocating 512 bytes would be slower than allocating double 64 times.
Usually the former would be still faster.
The point the author want to highlight here is that
although std::list triggers more allocations and deallocations, but modern malloc implementations
are very good at handling frequent small memory operations. In a sense, they are already doing
small objects pooling for you but transparently.
So, instead of “I am going to use std::deque because it is fast”,
measure before making a decision. The numbers might surprise you.
If std::list is already fast enough for you, even if it is still slightly slower,
you may still choose it because you prefer iterator stability.
Even if the standard allocator is not enough,
C++ already has a way to optimize memory allocation for C++ containers, that is, allocators.
Allocators are supposed to abstract away memory management for container types.
The problem with std::deque is that it is tied to a specific memory management strategy in a hard-coded way,
making it virtually impossible to use custom allocators with it.
An allocator for std::deque must handle 2 types of memory allocation,
one for the allocation of the internal pointer array,
and one for the allocation of fix-sized chunks, the size of which is an implementation detail that is not exposed to users.
If you want to make an optimized allocator for std::deque, you need to know what chunk size is used.
The size used in GCC’s libstdc++ is different than that of Clang’s libc++, which uses a chunk size of 4096 bytes.
Your implementation of a custom allocator for std::deque should not depends on an internal detail of it which
is intentionally hidden from you.
The argument here is not that you should use std::list, but that you could.
Actually, if you know your data size, you should consider a ring buffer (also called circular buffers) first.
Modern implementations of ring buffers often support capacity grow. It is only that users need to explicitly trigger reallocation.
For example, you can use set_capacity to grow capacity of a boost::circular_buffer.
If you need to push one million double numbers into a boost::circular_buffer, you can set its capacity to be big enough to hold
all of them. This will trigger a one-time memory allocation. While with std::deque, it will trigger at least 1 million / 64 = 15625 memory allocations.
std::deque does not expose a reserve API to users. Even if you know in advance how many elements you are going to push into a queue,
there is no way you can let std::deque to preserve memory and stop eager deallocation.
And when you pop out all the one million elements, std::deque will trigger at least 15625 - 1 (minus 1 for the keeping one chunk alive trick)
deallocations. With certain usage pattern and workload, the performance of std::deque can be disappointing.
For simple cases:
- First consider circular buffers. Elements are stored in contiguous memory (or in 2 pieces of contiguous memory), which makes it fast and random accessible.
Better, push and pop don’t invalidate iterators. Growing capacity will invalidate iterators, but that is under your control. Moreover, it does not frequently
grow and shrink like
std::deque. Usually, you have a good estimation of the size of data set of your application. Setting a big enough capacity at queue construction will suffice in most simple cases. - If it is really hard to predict an upper bound for queue size in your application,
and queues in your application can grow indefinitely,
consider
std::list(orstd::forward_listfor queue semantics) first. If performance is confirmed an issue after measurement, considerstd::pmr::list. If evenstd::pmr::listnot fast enough for you, consider using custom allocators withstd::list. Performance-wise, the biggest concern forstd::listis usually poor cache locality and repetitive memory allocation/deallocation. Custom allocators can greatly reduce the cost. Yes, even with custom allocators,std::listwould usually still be slower when elements are processed sequentially because of pointer chasing, but the performance difference can be within a small margin. The argument here is not you should usestd::listbecause it is faster thanstd::deque, but that if you can afford a bit worse performance, and stable iterator/pointer/reference ofstd::listis valuable for your use case, considerstd::list”, for its performance is not as bad as you might think while it enables more flexible design. Not every piece of code is super performance critical.
Go one step further
If you application is really performance critical, and circular buffers are too restrictive and std::list is too slow even with custom allocators,
we can go one step further to pursue a radical design.
Let us start with queues. We can make a queue by wrapping a std::vector<std::optional> like below.
The code sample is only to illustrate the idea, and intentionally incomplete.
Too much code would hide the core idea in implementation details.
Note it is for queue semantics, so it should be compared with std::queue instead of std::deque.
template<typename T>
class queue {
public:
template<typename... Args>
void emplace(Args&&... args) {
data_.emplace_back(std::in_place, std::forward<Args>(args)...);
}
void push(const T& value)
{
data_.emplace_back(value);
}
void push_back(T&& value)
{
data_.emplace_back(std::move(value));
}
void pop() {
if(!empty()){
data_[head_++].reset();
}
if (empty()) {
compact();
}
}
bool empty() const {
return head_ == data_.size();
}
std::size_t size() const {
return data_.size() - head_;
}
void compact() {
data_.erase(data_.begin(), data_.begin() + head_);
head_ = 0u;
}
private:
std::vector<std::optional<T>> data_;
std::size_t head_ = 0u;
};
With this design, the queue has the following properties trivially:
- All elements reside in a contiguous range of memory. It has good cache locality and fast iteration.
- It is random accessible but the iterator is lighter (because it is essentially just a pointer).
- Pushing elements might trigger reallocation and invalidate iterators just as
std::queue, but the cost of memory allocation of pushing n element is O(log(n)) contrasting to O(n) ofstd::queue. Because the capacity ofstd::vectorgrow geometrically while that ofstd::queuegrows linearly. In other words, our queue is friendlier for bulk operation. - “bulk-push-bulk-pop” cycles does not cause continuous allocation and deallocation cycles.
- Users can reserve capacity in advance to reduce reallocation.
- It works well with custom allocators.
The only drawback is that compaction only happens either when the queue is drained or when method compact is explicitly called.
So, with some peculiar usage patterns, for example, a sequence like “push 100 elements, pop 99 elements, repeat …” will cause trouble.
If this happens, you can always call compact when you see that the queue has become too sparse.
For example, you can add a push_might_compact method to the class, which, before pushing the element,
first checks whether head_ > 64 && size() * 4 < data_.size() and triggers compaction if so.
Obviously, compaction has real cost. If there is k elements in the queue when compaction happens, the cost is O(k).
The overall amortized cost depends on how often compaction happens. There is a short illustrative analysis in the paragraph below next paragraph
to show that is not as expensive as first glance.
std::optional is optional for nullable types and trivially destructible types.
- For a nullable type
T,std::vector<T>can be used. Whenpopis called, the element is set to the null value ofTfollowed byhead_increased. - For a trivially destructible type
T,std::vectorcan be used withpopbeing just increasehead_.
Let us use a queue of double as an example.
As stated above, the wrapped vector can be simplified to std::vector<double> as double is trivially destructible.
Now we construct a pathological operation sequence for the queue to intentionally trigger periodic compaction.
// when push, use the push_might_compact method
Init 1: push 80 elements;
Init 2: pop 65 elements;
Step 1: push 65 elements; // compaction triggered
Step 2: pop 65 elements;
Repeating Step 1-2
For operation sequence as such, there is one compaction happens at each push-pop cycle.
The compaction operation will be compiled to a memcpy of 15 doubles, that is a copy of 120 bytes.
On modern hardware, memcpy of such a size roughly costs 5-20ns.
That is roughly 0.08-0.27ns per element in average.
So, the cost is real, but the amortized cost is also quite insignificant.
When queue size grows, the latency spike caused by compaction will increase tail latency,
but average latency will only be slightly higher with pathological usage pattern.
This special operation sequence is comfort zone for std::deque because of the “keeping one backup chunk” optimization trick.
After allocating two chunks of 512 bytes, assuming we are using GCC, std::queue will recycle the one chunk released in Step 2.
From the point of memory allocation, this operation sequence happen to be optimal to std::queue.
But even with this operation sequence, std::queue generally won’t be faster, or only faster in jitter noise range depending on your setting-up,
as it has slower iterators in the sense of median or average latency, though it will have better tail latency.
But to be honest, for bounded queue size like this, a ring buffer will be the fastest.
If we use the following operation sequence by multiplying operation size of the above example by 10,
while the amortized cost of compaction is still the same for our queue, the cost of repeating memory allocation and deallocation will kick in for std::queue.
Even with the “keeping one backup chunk trick”, 11 chunks of 512 bytes will be allocated and deallocated per cycle.
This will roughly cost 400-4000ns in total, while memcpy of 160 double’s will roughly cost 20-400ns.
// when push, use the push_might_compact method
Init 1: push 800 elements;
Init 2: pop 650 elements;
Step 1: push 650 elements; // compaction triggered
Step 2: pop 650 elements;
Repeating Step 1-2
We can see that as data size grows, the downside of std::queue becomes more apparent.
The key insight here is that repetitive memory relocating is faster repetitive memory allocation/deallocation.
Moreover, the above is worst-case analysis. With many usage pattern and work loads,
compaction either never happens or happens only rarely.
But, doesn’t an auto-growing curcular buffer have all the benefits stated above without the trouble of compaction? Yes and No. Obviously, auto-growing circular buffers can be better for some usage patterns. But this design has different spatial cache locality characteristics while both can handle unbounded input bursts. Say, after an input burst, the size of a ring buffer is enlarged to 1 million, system enters small-volume mode, with a pattern that is roughly as below:
push 100
pop 100
push 10
pop 10
push 23
pop 23
That is, small active data set in a large queue. Due to the nature of ring buffers, the sliding window consisting of active data moves over the underlying array from begin to end until wrap-up and repeat. Since the queue size is large, it keeps invalidating L1/L2 cache lines. This is something that does not show with big O notation of algorithm analysis. While our queue, with seemingly unnecessary compaction sometimes, tries to keep active data near front of the underlying array. With the operation sequence above, our queue only access a small portion the buffer at its begining. This is much faster because cache line is hot.
With two vectors arranged head-to-head, deque can also be implemented with the same idea.
Code is omitted here. I don’t want to make this post unnecessarily long.
To sum up, When you can easily come up with better alternatives,
it might be a strong indicator that std::deque and std::queue are not well designed.
But isn’t reference stability of std::deque still something unique?
Someone might say that there is something unique to std::queue that has been neglected by us by now, that is, reference stability.
Reference stability means that once you get a reference or a pointer to an element in std::queue, it will remain valid during the
lifetime of the queue, as long as the referenced element is not popped out.
Can this be a valid reason that std::deque should be preferred in some cases?
But, with a small trick, the iterator of our queue proposed in last section can be made stable.
If, instead of reusing the iterator of std::vector, we define the iterator of the queue as
a pair of pointer and index, where the pointer pointing to data_ and the index being n,
meaning the n-th element that has been pushed since queue creation, like below:
class iterator{
decltype(data_) * ptr = &data_;
std::size_t n; // the n-th element pushed into queue ever
};
We also need to maintain a std::size_t push_index and a std::size_t pop_index inside the queue.
Whenever an element is pushed into the queue, push_index is increased by 1,
and pop_index increased by 1 when an element is popped out.
The relation of size() == push_indx - pop_index is always true.
Thus an iterator of index n points to the element at slot head_ + (n - pop_index).
With this definition, iterators are stable under all queue operations.
Iterators of this type also have the advantage that you can check whether the pointed-to element has been popped out,
by comparing them with begin() and end().
Of course, iterator stability is not the same as reference stability. But, in code where you store a reference or pointer, you can always store a iterator instead. When you hold a reference or pointer, you have to pay extra attention to make sure that the referenced object has not been popped out, otherwise, you will have a use-after-free bug. When you hold an iterator, you can check whether the iterator is still valid. There is one caveat though, iterators will be invalidated if the queue is moved.
Another drawback of our queue is that it does not work with non-movable types like std::mutex.
But, honestly, when is the last time you have to push and pop a large number of std::mutex objects.
There are not many non-movable types in real world programming.
When you do need to deal with them with a queue in some rare cases, consider fixed-size circular buffers or std::list.