小编emi*_*een的帖子

为什么 SortedList 上的 foreach() 与 Dictionary 相比内存如此昂贵?

在优化网站时,我尝试使用 Benchmark.Net 对代码进行基准测试。但我惊讶地发现一些基准测试代码使用的内存多了 40,000 倍。经过太多的基准测试后,我发现内存分配是由于对 SortedList<int, int> 进行 foreach 造成的。

using BenchmarkDotNet.Attributes;

namespace NetCollectionsBenchmarks
{
    [MemoryDiagnoser]
    public class CollectionsBenchmarks
    {
        private Dictionary<int, int> DictionaryData = new();
        private SortedList<int, int> SortedListData = new();

        private Dictionary<int, int> DictionaryCheck = new();
        private SortedList<int, int> SortedListCheck = new();

        [GlobalSetup]
        public void Setup()
        {
            for (int x = 0; x < 15; x++)
                this.DictionaryData.Add(x, x);

            this.SortedListData = new SortedList<int, int>(this.DictionaryData);

            this.DictionaryCheck = new Dictionary<int, int>(this.DictionaryData);
            this.SortedListCheck = new SortedList<int, int>(this.DictionaryData);
        }

        [Benchmark(Baseline = true)]
        public …
Run Code Online (Sandbox Code Playgroud)

c# sortedlist

7
推荐指数
1
解决办法
238
查看次数

标签 统计

c# ×1

sortedlist ×1