How do .NET's Queue<T> and Stack<T> store items internally, and what does Enqueue or Push cost when the backing array is full?
answer
- one array, not nodes
- head and tail wrap around
- double, then copy
- removal never shrinks
basics
~20 sStack<T> fills a T[] upward from index 0; Queue<T> treats a T[] as a circular buffer with wrapping head and tail indexes. When full, each allocates a double-size array and copies, so adds are amortized O(1).
solid answer
~40 sBoth wrap one array. `Stack<T>` pushes at index `Count` and pops from the end, so nothing moves. `Queue<T>` keeps head and tail indexes that wrap around the end of its array, a circular buffer, so `Dequeue` is O(1) and never shifts items. When the array is full, the next `Enqueue` or `Push` allocates a bigger one (4 slots first, then double; the queue also grows by at least 4) and copies everything, an O(n) step that averages out to amortized O(1). Removal never shrinks the array: `Dequeue` and `Pop` only clear the vacated slot when `T` holds references, so the GC can collect the item. To give memory back after a spike you call `TrimExcess()`, which reallocates when `Count` is under 90% of capacity.
code
csharp · 17 linesvar queue = new Queue<int>();
var stack = new Stack<int>();
ReportGrowth("Queue<int>", i => queue.Enqueue(i));
ReportGrowth("Stack<int>", i => stack.Push(i));
static void ReportGrowth(string name, Action<int> add)
{
add(1); // item #1 allocates the first 4-slot array and warms up the lambda
var growth = new List<int>();
for (int i = 2; i <= 40; i++)
{
long before = GC.GetAllocatedBytesForCurrentThread();
add(i);
if (GC.GetAllocatedBytesForCurrentThread() != before) growth.Add(i);
}
Console.WriteLine($"{name} grew on item #{string.Join(", #", growth)}");
}go deeper
Remember that both types sit on a single array and that adds are usually O(1), with an occasional copy when the array fills up.
Explain the circular buffer with wrapping head and tail, the 4-then-double growth, amortized O(1) adds, and why Dequeue never shifts items.
Recognise the memory a queue keeps after a spike, know that only TrimExcess shrinks it, and presize with the capacity constructor when the volume is known.
Weigh memory retention against reallocation churn for long-lived queues in services, and set guidance on presizing and trimming rather than leaving it to chance.
## Two arrays, two layouts Neither `Queue<T>` nor `Stack<T>` is built from linked nodes. Each wraps a single `T[]` plus a few integer fields, which is why both are cheap and cache-friendly. - **`Stack<T>`** keeps `_array` and `_size`. The bottom item sits at index 0 and the top at `_size - 1`. `Push` writes at `_size` and increments it; `Pop` decrements it. Nothing ever moves. - **`Queue<T>`** keeps `_array`, `_head`, `_tail` and `_size`, and treats the array as a **circular buffer**. `Enqueue` writes at `_tail` and advances it; `Dequeue` reads at `_head` and advances it. When either index reaches the end of the array it wraps to 0 (the source does this with a comparison, not `%`, for speed). So a queue that has seen thousands of enqueues and dequeues can still be using its first small array, with the live items "wrapped around" the end. That is the key difference from a naive array queue: `Dequeue` never shifts the remaining items left. It is O(1) every time. ## What happens when the array is full Both types start with an empty array when you use the parameterless constructor and allocate on the first add. When `Count` equals the array length, the next add calls a private `Grow` method: | Type | First allocation | Growth rule | Copy on growth | |---|---|---|---| | `Stack<T>` | 4 slots | double the length | `Array.Resize` copies items in place order | | `Queue<T>` | 4 slots | double the length, at least 4 more | `SetCapacity` copies head-to-end, then start-to-tail, so the new array starts at index 0 | Growth costs one allocation and an O(n) copy, but because the size doubles, the total copying across n adds stays proportional to n, so `Enqueue` and `Push` are **amortized O(1)** with an occasional O(n) step. The allocation counter in the example sees new arrays on the 5th, 9th, 17th and 33rd add: capacities 4, 8, 16, 32, 64. You can watch this without any internal API. `GC.GetAllocatedBytesForCurrentThread()` returns the bytes the current thread has allocated so far, so reading it before and after each add shows exactly which adds allocated a new backing array; the adds in between allocate nothing, because they only write into a free slot. That is a more trustworthy demonstration than timing a loop with a stopwatch, which measures noise as much as copying. If you know the size up front, `new Queue<T>(capacity)` or `new Stack<T>(capacity)` allocates once; `EnsureCapacity(int)` grows an existing instance in one step. The capacity is a starting size, not a limit: adding past it simply grows the array. ## Removal never gives memory back 1. `Dequeue` and `Pop` move an index and decrement `_size`; the array keeps its length. 2. When `T` is a reference type or a struct containing references (`RuntimeHelpers.IsReferenceOrContainsReferences<T>()`), they also write `default` into the vacated slot, so the removed object is no longer reachable through the queue and can be garbage-collected once your code drops it. For `int` this step is skipped because there is nothing to free. 3. `TrimExcess()` is the only way to shrink an existing instance: it reallocates to exactly `Count` when `Count` is below 90% of the current length, and does nothing otherwise. So a print-shop queue that briefly held 50,000 jobs during a paper outage keeps an array of 65,536 slots afterwards, even with three jobs left. Those slots are mostly `null` references, cheap per slot but real memory for a long-lived service; call `TrimExcess()` after a known spike if that matters. ## Costs worth stating precisely - `Enqueue`, `Dequeue`, `Push`, `Pop`, `Peek`, `Count`: O(1), with growth making adds amortized O(1). - `Contains(T)`: O(n), a scan using `EqualityComparer<T>.Default` (the queue checks both halves of a wrapped buffer). - `ToArray()` and `CopyTo`: O(n); the queue copies in up to two pieces to unwrap the circle. - `Clear()`: O(1) for value types without references; for reference types it clears the occupied slots so the GC can reclaim them. - No indexer and no middle removal: the layout would make them awkward, so the API leaves them out. ## Why it matters The circular buffer is why `Queue<T>` beats a `List<T>` used as a queue: `list.RemoveAt(0)` shifts every remaining element, an O(n) memory move per dequeue, while `Queue<T>.Dequeue` just advances `_head`. And the no-shrink rule is why a queue that spiked once can hold memory long after the spike ended.
- Why does Queue<T>.Dequeue write default into the slot it just read?The array outlives the item. If the slot kept its reference, the dequeued object would stay reachable through the queue's array and could not be garbage-collected until that slot was overwritten. The source does this only when `RuntimeHelpers.IsReferenceOrContainsReferences<T>()` is true; for an `int` queue there is nothing to release, so it skips the write.
- Why is Queue<T> a better FIFO than a List<T> with RemoveAt(0)?`List<T>.RemoveAt(0)` shifts every remaining element one slot left, an O(n) memory move on each dequeue. `Queue<T>.Dequeue` reads the head slot and advances the head index, wrapping at the end of the array, so it is O(1) regardless of how many jobs are waiting.
- Queue<T>.Dequeue shifts every remaining element one slot left.
- Queue<T> is a linked list of nodes, so Enqueue never copies.
- A Queue<T> shrinks its array automatically once most items are dequeued.
- Enqueue is O(1) every time, with no occasional copy.
- The capacity passed to the constructor caps how many items fit.