It seems that Dictionary<,> performance is affected by the size of the item being stored (which seems bizarre).
Here's 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'll change 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 object construction takes 1.72x longer, but adding to the Dictionary takes 6.11x longer. I expected the tests to take longer, but why does the Dictionary take so much longer to add larger objects?