【发布时间】:2011-08-25 14:17:50
【问题描述】:
字典的性能似乎受到所存储项目大小的影响(这看起来很奇怪)。
这是我的简单课程:
public class MyObject
{
public Guid Key { get; set; }
}
还有两个简单的测试:
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);
}
}
最初我得到以下时间:
ShouldTestDefaultConstructorPerformance : 00:00:00.580
ShouldTestDefaultGuidDictionaryPerformance : 00:00:01.238
现在,我将更改 MyObject 类:
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>();
}
然后再次运行测试:
ShouldTestDefaultConstructorPerformance : 00:00:01.333
ShouldTestDefaultGuidDictionaryPerformance : 00:00:07.556
在第二个测试中,对象构造的时间延长了 1.72 倍,但添加到字典需要 6.11 倍的时间。我预计测试需要更长的时间,但为什么字典需要 so 更长的时间来添加更大的对象?
【问题讨论】:
-
这会测试对象的创建以及插入到字典中。您还没有将一个与另一个隔离开来。
-
不完全是一个公平的比较,因为在第二个测试中,您分配了
iterations*<object size>,而在第一种情况下(取决于运行时引擎和优化),您正在重用相同的内存空间。更好的性能比较是测试一的对象数组,测试二的字典......我想你会发现性能更接近。
标签: c# performance dictionary