C# Dictionary Memory

Dictionary illustration

You want to determine how much memory is used by the Dictionary collection in the C# programming language when you set its capacity. Setting the capacity of Dictionary at runtime is an excellent way to optimize performance, but it can require excess memory.

Capacity memory

This program allocates a Dictionary field three times: first, with no capacity; second, with a capacity of 1000; and third, with a capacity of 10000. The program then prints how much memory was allocated at each of the three steps.

Program that tests Dictionary memory [C#]

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);

	// 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

Results. The program shows that a Dictionary with zero capacity only required 52 bytes. A Dictionary with 1000 capacity required 22084 bytes—approximately 22 bytes per unit of capacity. A Dictionary with 10000 capacity required about 18 bytes per unit of capacity.

Question and answer

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.

Prime Number

Summary

Note

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. Therefore, if you choose to use a capacity optimization, an overly large capacity could cause memory problems.

Collections
.NET