In C#, Dictionary.TrimExcess() shrinks the inside storage of a dictionary so that it fits the pairs that are really there. It helps after you have removed many items and the dictionary still holds on to a lot of empty space.
It does not remove any pairs. All your keys and values stay exactly the same; only the unused memory is released. It is the partner of EnsureCapacity().
This is an instance member of Dictionary<TKey,TValue> (System.Collections.Generic). Call it on a dictionary variable, such as ages.TrimExcess(...). A dictionary is a class, so two variables can share one dictionary. TrimExcess exists in .NET 5 and later. It is not in .NET Framework.
Syntax
There are two forms: no argument, or a target capacity.
C#
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.EnsureCapacity(1000);
ages.Add("Asha", 25);
ages.TrimExcess(); // shrink to fit Count
ages.TrimExcess(10); // shrink to about 10, never below Count
Call
What it does
ages.TrimExcess()
Shrinks the storage to fit the current number of pairs.
ages.TrimExcess(10)
Shrinks to at least 10 spaces. Throws if 10 is smaller than Count.
ages.Clear()
Removes all pairs but keeps the capacity; follow it with TrimExcess() to release memory.
Trimming rebuilds the inside tables, so it costs time. Do it once after a big clean-up, not inside a loop. If the target capacity is smaller than Count, ArgumentOutOfRangeException is thrown.
Library declarations
C#
public void TrimExcess();
public void TrimExcess(int capacity);
Parameters
Parameter
Description
capacity
Optional (second overload). The target capacity. It must be at least Count. The no-argument form shrinks to fit Count.
Return Value
Return Value
Description
void
Nothing is returned. Count and all pairs are unchanged.
C# Examples
Example 1 — Trim a Dictionary with Extra Space
Reserve a lot of room, add only three pairs, trim, and confirm that the data did not change.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.EnsureCapacity(1000);
ages.Add("Asha", 25);
ages.Add("Ravi", 31);
ages.Add("Meena", 28);
ages.TrimExcess();
Console.WriteLine(ages.Count);
Console.WriteLine(ages["Asha"]);
Console.WriteLine(ages.ContainsKey("Ravi"));
}
}
Output
3
25
True
How It Works
Big reserve.EnsureCapacity(1000) makes space for far more pairs than the three that are added.
One trim call.TrimExcess() rebuilds the storage so that it is just large enough for 3 pairs.
Pairs unchanged.Count is still 3 and ages["Asha"] still gives 25.
Lookups still work.ContainsKey("Ravi") is True, since trimming does not touch keys or values.
Example 2 — Trim After Removing Most Entries
Fill a dictionary with 1000 pairs, remove 990 of them, and then release the extra space.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<int, string> items = new Dictionary<int, string>();
for (int i = 0; i < 1000; i++) {
items.Add(i, "item" + i);
}
for (int i = 0; i < 990; i++) {
items.Remove(i);
}
items.TrimExcess();
Console.WriteLine(items.Count);
Console.WriteLine(items.ContainsKey(995));
Console.WriteLine(items.ContainsKey(5));
Console.WriteLine(items[999]);
}
}
Output
10
True
False
item999
How It Works
Grow big. Adding 1000 pairs makes the dictionary reserve a lot of space.
Remove most. Keys 0 to 989 are removed. Removing pairs does not give the memory back by itself.
Trim once.TrimExcess() now shrinks the storage to match the 10 pairs that are left.
Survivors are intact. Keys 990 to 999 remain, so ContainsKey(995) is True, ContainsKey(5) is False, and items[999] is item999.
Example 3 — TrimExcess with a Target Capacity
Pass a number to TrimExcess(int). A target below Count throws; a safe target works.
C#
using System;
using System.Collections.Generic;
class Program {
static void Main() {
Dictionary<string, int> ages = new Dictionary<string, int>();
ages.Add("Asha", 25);
ages.Add("Ravi", 31);
ages.Add("Meena", 28);
try {
ages.TrimExcess(2);
} catch (ArgumentOutOfRangeException) {
Console.WriteLine("Capacity too small");
}
ages.TrimExcess(10);
Console.WriteLine("Trimmed to 10 ok");
Console.WriteLine(ages.Count);
}
}
Output
Capacity too small
Trimmed to 10 ok
3
How It Works
Three pairs stored. A dictionary cannot be smaller than its own Count, so the lowest valid target here is 3.
Too small.TrimExcess(2) asks for room for only 2 pairs, so it throws ArgumentOutOfRangeException.
Safe target.TrimExcess(10) is at least Count, so it works and the program prints a success line.
Data kept. The final Count is still 3, because trimming never deletes pairs.
Frequently Asked Questions
It reduces the unused space in a dictionary so that the storage fits the number of pairs it holds. It does not remove any pairs.
Call it once after you have removed most items from a large dictionary that will stay small. Do not call it in a loop.
It shrinks the dictionary to the capacity you pass, but never below Count. A capacity smaller than Count throws ArgumentOutOfRangeException.
No. Clear keeps the capacity. Call TrimExcess after Clear if you want to release the space.
Use .NET 5 or later to be safe. It is not in .NET Framework.