使用Dictionary<>的奇怪性能结果

时间:2011-08-25 14:17:50

标签: c# performance dictionary

似乎词典<,> 的效果会受到所存储项目大小的影响(这看起来很奇怪)。

这是我的简单课程:

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倍。我希望测试需要更长的时间,但为什么字典需要所以更长时间才能添加更大的对象?

4 个答案:

答案 0 :(得分:1)

我认为人们需要更仔细地阅读问题,而不是急于发布答案。如果仔细查看他的示例代码(BOTH测试),将MyObject与Guid和MyObject与Guid和10 Dict的区别在于他的循环的第二个(对象构造)。但是,添加字典至少还要占用5秒钟。

答案 1 :(得分:0)

我认为var obj = new MyObject() { Key = Guid.NewGuid() };此行实际上需要更长时间而不是Add()字典。您是否在提供了内部方法?

答案 2 :(得分:0)

我认为我的答案是:使用分析器并确定哪个位实际需要更长的时间

这可能会突出实例化。也许:))

答案 3 :(得分:-2)

您添加到字典中的每个对象都会获得一个特殊的唯一标识符,以加快其在内存中的搜索和检索速度。通过分析对象的整个内容来计算该特殊唯一标识符(称为散列)。对象越大,计算哈希的速度就越慢。

如果您对其工作原理的详细信息感兴趣,请查看大学课程中的此示例:http://www.ccs.neu.edu/home/sbratus/com1101/hash-dict.html