In C#, Queue.TrimExcess() shrinks the queue's internal storage so it fits the number of items it holds right now. It is the opposite of EnsureCapacity().
A queue that once held a million jobs keeps its big array even after you process most of them, because Dequeue() and Clear() do not hand memory back. Think of a long bench that stays in the hall after the crowd went home. TrimExcess swaps it for a small one. The items, their order, and Count do not change.
This is an instance member of Queue<T> (System.Collections.Generic). Call it on a queue variable, such as line.TrimExcess(...). A Queue<T> is a class, so two variables can share one queue. It is first in, first out (FIFO): items leave in the order they arrived. It is not thread-safe; for several threads use ConcurrentQueue<T>.
Syntax
Call TrimExcess with no arguments after the queue has become much smaller.
C#
Queue<int> queue = new Queue<int>();
for (int i = 0; i < 1000; i++) queue.Enqueue(i);
while (queue.Count > 3) queue.Dequeue(); // only 997, 998, 999 are left
queue.TrimExcess(); // shrink the storage to fit 3 items
Call
What it does
queue.TrimExcess()
Shrinks the storage to fit the current Count. Items stay in order.
TrimExcess may copy the items into a new, smaller array, so it costs time proportional to the number of items. It only shrinks when there is a good amount of unused space (the queue must be clearly below its capacity), otherwise it may do nothing. Call it once after a big clean-up, not inside a loop. A Queue<T> has no public Capacity property, so you cannot see the change, only the memory profile does.
Library declarations
C#
public void TrimExcess();
Parameters
Parameter
Description
None
TrimExcess() takes no parameters.
Return Value
Return Value
Description
void
Nothing is returned. The items, their order, and Count are the same as before the call.
C# Examples
Example 1 — Trim a Queue After Most Items Are Served
Fill a queue with 1000 numbers, serve all but the last three, and call TrimExcess. The remaining items are unchanged.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Queue<int> queue = new Queue<int>();
for (int i = 0; i < 1000; i++) {
queue.Enqueue(i);
}
while (queue.Count > 3) {
queue.Dequeue();
}
queue.TrimExcess();
Console.WriteLine(queue.Count);
Console.WriteLine(queue.Peek());
Console.WriteLine(string.Join(", ", queue));
}
}
Output
3
997
997, 998, 999
How It Works
Big queue first. The loop enqueues 0 to 999, so the queue reserved a lot of storage for 1000 items.
Serve nearly all. The while loop dequeues until only 3 items remain. The storage is still large afterward.
Give space back.TrimExcess() shrinks the storage to fit 3 items. It prints nothing and changes no item.
Same answers.Count is 3, the front is 997, and the order is still 997, 998, 999.
Example 2 — Trim an Empty Queue and Use It Again
Clear a queue, trim it, and keep working with it. See that trimming an empty queue is safe.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Queue<string> words = new Queue<string>();
words.Enqueue("alpha");
words.Enqueue("beta");
words.Enqueue("gamma");
words.Clear();
words.TrimExcess();
Console.WriteLine(words.Count);
words.TrimExcess();
words.Enqueue("delta");
Console.WriteLine(words.Count);
Console.WriteLine(words.Peek());
}
}
Output
0
1
delta
How It Works
Empty first.Clear() removes the items but keeps the array. TrimExcess() then lets the extra space go.
Safe on empty. Trimming a queue with no items raises no error, and the first printed Count is 0.
Trim twice. The second TrimExcess() has nothing left to shrink, so it does nothing harmful.
Still usable. The queue simply gets storage again when it needs it. Enqueue("delta") works, Count is 1, and delta is the front.
Example 3 — Build a Backlog, Keep the Latest, Trim Once
A method loads 1000 numbers, drops the oldest ones until 10 are left, trims once, and returns the small queue.
C#
using System;
using System.Collections.Generic;
class Program {
static Queue<int> BuildRecent() {
Queue<int> recent = new Queue<int>();
for (int i = 0; i < 1000; i++) {
recent.Enqueue(i);
if (recent.Count > 10) {
recent.Dequeue();
}
}
recent.TrimExcess();
return recent;
}
static void Main() {
Queue<int> recent = BuildRecent();
Console.WriteLine(recent.Count);
Console.WriteLine(recent.Peek());
Console.WriteLine(recent.Contains(995));
Console.WriteLine(recent.Contains(5));
}
}
Output
10
990
True
False
How It Works
A sliding window. Each number is enqueued, and as soon as the queue has more than 10 items the oldest one is dequeued. This keeps only the 10 latest numbers.
Which ones stay. At the end the queue holds 990 to 999, so Count is 10 and Peek() shows 990.
Trim at the end. The method calls TrimExcess() one time, right before returning, because that is when the queue is final and small.
Lookups.Contains(995) is True, while Contains(5) is False because the early numbers were dropped long ago.
Frequently Asked Questions
It shrinks the internal storage of the queue so it fits the number of items it holds now. The items, their order, and Count stay exactly the same.
No. It never removes or changes an item. It only releases unused storage space.
Once, after a big clean-up that left a once-large queue small for a long time. Do not call it inside a loop, because copying the items takes time.
Clear removes the items but keeps the storage. Call TrimExcess after Clear if you also want to give the space back.
Not with a Queue<T>. It has no public Capacity property, so the effect shows up in memory use rather than in your program output.