Dictionary <,> seems to be affected by the size of the stored element (which seems strange).
Here is my simple class:
public class MyObject { public Guid Key { get; set; } }
And two simple tests:
private long _Iterations = 1000000; [TestMethod] public void ShouldTestDefaultConstructorPerformance() { for (var i = 0; i < _Iterations; i++) { var obj = new MyObject() { Key = Guid.NewGuid() }; } } [TestMethod] public void ShouldTestDefaultGuidDictionaryPerformance() { var dict = new Dictionary<Guid, MyObject>(); for (var i = 0; i < _Iterations; i++) { var obj = new MyObject() { Key = Guid.NewGuid() }; dict.Add(obj.Key, obj); } }
Initially, I get the following timings:
ShouldTestDefaultConstructorPerformance : 00:00:00.580 ShouldTestDefaultGuidDictionaryPerformance : 00:00:01.238
Now I will change the MyObject class:
public class MyObject { public Guid Key { get; set; } private Dictionary<string, string> _Property0 = new Dictionary<string, string>(); private Dictionary<string, string> _Property1 = new Dictionary<string, string>(); private Dictionary<string, string> _Property2 = new Dictionary<string, string>(); private Dictionary<string, string> _Property3 = new Dictionary<string, string>(); private Dictionary<string, string> _Property4 = new Dictionary<string, string>(); private Dictionary<string, string> _Property5 = new Dictionary<string, string>(); private Dictionary<string, string> _Property6 = new Dictionary<string, string>(); private Dictionary<string, string> _Property7 = new Dictionary<string, string>(); private Dictionary<string, string> _Property8 = new Dictionary<string, string>(); private Dictionary<string, string> _Property9 = new Dictionary<string, string>(); }
And run the tests again:
ShouldTestDefaultConstructorPerformance : 00:00:01.333 ShouldTestDefaultGuidDictionaryPerformance : 00:00:07.556
In the second test, the construction of the object takes more than 1.72x, but adding a dictionary takes 6.11x more . I expected the tests to take longer, but why does the Dictionary take much longer to add large objects?