具有初始容量的字典

swi*_*tgp 1 .net vb.net

我读到,如果可以估计大小,则用初始容量初始化字典可能会带来更好的性能。

Dim MyDataTable As New DataTable

'Fill MyDataTable from Database

Dim CapacityEstimate As integer = MyDataTable.Rows.Count
Dim MyDictionary As New Dictionary(Of String, MyObjectType)(CapacityEstimate)

'Fill the Dictionary independent of data table
Run Code Online (Sandbox Code Playgroud)

CapacityEstimate 变量只是字典应保存的键/值对数量的估计(通常在 2500 到 7000 范围内)。因此,如果我估计它是 4000 个对象,最终有 4010 个对象(我可能会超过或低于,不确定),字典会使用大量内存来调整其中已有的许多键/值对的大小。这是一个好的解决方案还是我最好不要用初始容量初始化它。谢谢。

编辑:相关但不相同 - .NET 通用字典是否应该使用等于它将包含的项目数的容量进行初始化?

And*_*lil 5

这是个好问题。我没有到处搜索,但奥德的回答对我来说似乎不错。

不过,让我们对其运行一个概念性的微基准测试:

        Dictionary<string, int> FixedCapacity = new Dictionary<string, int>(4000);
        Dictionary<string, int> NotFixedCapacity = new Dictionary<string, int>();

        Stopwatch stopWatch = new Stopwatch();

        stopWatch.Start();

        for (int i = 0; i < 5000; i++)
        {
            FixedCapacity.Add(i.ToString(), i);
        }

        stopWatch.Stop();

        Console.WriteLine(string.Format("Fixed initial capacity: {0} ms", stopWatch.ElapsedMilliseconds));

        stopWatch.Reset();

        stopWatch.Start();

        for (int i = 0; i < 5000; i++)
        {
            NotFixedCapacity.Add(i.ToString(), i);
        }

        stopWatch.Stop();

        Console.WriteLine(string.Format("Not Fixed initial capacity: {0} ms", stopWatch.ElapsedMilliseconds));

        Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

结果:

Fixed initial capacity: 1ms
Not Fixed initial capacity: 1ms
Run Code Online (Sandbox Code Playgroud)

这是另一个很好的答案,IMO =)

免责声明:不,这不是一个完整的基准测试程序,我只是在一台机器上测量框架的“默认”行为。我已经手动运行了几次并得到了相同的结果,即使它不在循环中。如果您有更好的基准测试工具,请测试它并将结果粘贴到此处。