TheDeveloperBlog.com

C# Dictionary Memory

Dictionary memory. A Dictionary uses memory space to improve performance. And increasing the capacity of Dictionary at runtime is an excellent way to optimize performance. This requires even more excess memory. We investigate this tradeoff.

Capacity

Example. This program allocates a Dictionary field three times. First it uses no capacity. Second it uses a capacity of 1000. And third it uses a capacity of 10000. The program then prints how much memory was allocated at each step.

Console.WriteLine
```C# program that tests Dictionary memory

using System;
using System.Collections.Generic;

class Program
{
static Dictionary<string, int> _d;
static void Main()
{
long m1 = GC.GetTotalMemory(true);
{
_d = new Dictionary<string, int>();
}
long m2 = GC.GetTotalMemory(true);
{
_d = new Dictionary<string, int>(1000);
}
long m3 = GC.GetTotalMemory(true);
{
_d = new Dictionary<string, int>(10000);
}
long m4 = GC.GetTotalMemory(true);

// Display results.
Console.WriteLine("Capacity: {0}, Memory: {1}", 0, m2 - m1);
Console.WriteLine("Capacity: {0}, Memory: {1}", 1000, m3 - m2);
Console.WriteLine("Capacity: {0}, Memory: {1}", 10000, m4 - m3);
}
}

Output

Capacity: 0, Memory: 52
Capacity: 1000, Memory: 22084
Capacity: 10000, Memory: 180004```

A Dictionary with zero capacity only used 52 bytes. A Dictionary with 1000 capacity required 22084 bytes—approximately 22 bytes per unit of capacity. With 10000 capacity, it required about 18 bytes per unit of capacity.

Byte

Discussion. Why is the relation not linear? The capacity doesn't result in a certain number of bytes per unit because in its implementation, the Dictionary changes the capacity you use to a prime number.

Therefore: The actual capacity is not 1000 or 10000 in these examples—it is a value close to those specified.

Prime Number

Summary. If you choose to allocate a Dictionary(string, int) with a large capacity, you will be requiring about 20 bytes per unit of capacity. Other Dictionary types with different type parameters are likely very similar.

Warning: If you choose to use a capacity optimization, an overly large capacity could cause memory problems.