Created
April 17, 2018 02:22
-
-
Save waf/bb1f3ef3a1e2818fe7d34b87abea5197 to your computer and use it in GitHub Desktop.
Testing memory usage when iterating IDictionary vs Dictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
const int trials = 1_000_000; | |
static void Main(string[] args) | |
{ | |
Dictionary<int, string> dict = Enumerable | |
.Range(1, 10) | |
.ToDictionary(number => number, number => number.ToString()); | |
var idict = (IDictionary<int, string>)dict; | |
Console.ReadKey(); | |
// test iterating interface type | |
GC.Collect(); | |
Test(idict); | |
long idictMem = GC.GetTotalMemory(forceFullCollection: false); | |
// test iterating concrete type | |
GC.Collect(); | |
Test(dict); | |
long dictMem = GC.GetTotalMemory(forceFullCollection: false); | |
Console.WriteLine($"Dictionary: {dictMem} bytes, IDictionary: {idictMem} bytes, IDictionary uses {idictMem/dictMem}x more memory"); | |
// output on my machine: "Dictionary: 30616 bytes, IDictionary: 579480 bytes, IDictionary uses 18x more memory" | |
Console.ReadKey(); | |
} | |
private static void Test(Dictionary<int, string> dict) | |
{ | |
for (int i = 0; i < trials; i++) | |
{ | |
foreach (var kvp in dict) | |
{ | |
// do something with key or values | |
} | |
} | |
} | |
private static void Test(IDictionary<int, string> dict) | |
{ | |
for (int i = 0; i < trials; i++) | |
{ | |
foreach (var kvp in dict) | |
{ | |
// do something with key or values | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment