HomeSearch

C# Dictionary Memory

Determine approximately how much memory the capacity setting on Dictionary requires.
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.DictionaryOptimization
Notes, capacity. With more memory usage, we can reduce hash collisions and speed up lookups on Dictionary. But as with all performance optimizations, this must be measured.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.

Then: The program prints (with Console.WriteLine) how much memory was allocated at each step.

Console

GC: We invoke GC.GetTotalMemory with an argument of "true" to force a full garbage collection at each measurement.

GC.Collect

Result: Each unit of capacity uses less memory on average as the capacity is increased to greater levels.

Byte

Note: For .NET Core in 2020, the memory usage for capacity unit has increased to about 30 bytes (from 20 for older .NET Frameworks).

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: 72 Capacity: 1000, Memory: 31008 Capacity: 10000, Memory: 283008
A discussion. 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
A summary. If you choose to allocate a Dictionary(string, int) with a large capacity, you will be requiring about 30 bytes per unit of capacity.
Other Dictionary types with different type parameters are likely very similar. If you choose to use a capacity optimization, an overly large capacity could cause memory problems.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.