【问题标题】:Why does sortedDictionary need so much overhead?为什么 sortedDictionary 需要这么多开销?
【发布时间】:2011-05-11 08:27:04
【问题描述】:
long b = GC.GetTotalMemory(true);
SortedDictionary<int, int> sd = new SortedDictionary<int, int>();
for (int i = 0; i < 10000; i++)
{
    sd.Add(i, i+1);
}
long a = GC.GetTotalMemory(true);
Console.WriteLine((a - b));            
int reference = sd[10];    

输出(32 位):

280108

输出(64 位):

480248

单独存储整数(在数组中)大约需要 80000 个。

【问题讨论】:

  • 因为它是一棵树。还有一个 SortedList 和一个恰好被排序的普通 List(确保将项目插入到正确的位置)

标签: c# memory-management sorteddictionary


【解决方案1】:

在内部 SortedDictionary&lt;TKey, TValue&gt; 使用 TreeSet&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;。树使用Node&lt;T&gt;,显然它使用节点之间的引用,因此除了每个键和值之外,您还将引用左右节点以及一些附加属性。 Node&lt;T&gt; 是一个类,因此每个实例都具有引用类型的传统开销。此外,每个节点还存储一个名为IsRed 的布尔值。

根据 WinDbg/SOS,单个节点的大小为 64 位,48 个字节,因此其中 10000 个将占用至少 480000 个字节。

0:000> !do 0000000002a51d90 
Name:            System.Collections.Generic.SortedSet`1+Node[[System.Collections.Generic.KeyValuePair`2[[System.Int32, mscorlib],[System.Int32, mscorlib]], mscorlib]]
MethodTable: 000007ff000282c8
EEClass:     000007ff00133b18
Size:        48(0x30) bytes     <== Size of a single node
File:            C:\windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll
Fields:
              MT    Field   Offset                 Type VT     Attr            Value     Name
000007feeddfd6e8  4000624       18       System.Boolean  1 instance                0     IsRed
000007feee7fd3b8  4000625       20 ...Int32, mscorlib]]  1 instance 0000000002a51db0 Item
000007ff000282c8  4000626        8 ...lib]], mscorlib]]  0 instance 0000000002a39d90 Left
000007ff000282c8  4000627       10 ...lib]], mscorlib]]  0 instance 0000000002a69d90 Right

【讨论】:

  • 它的功能真的需要这个开销吗?
  • @Willem:我想真正的问题是;你需要 SortedDictionary 的所有功能吗?如果不是,则有一些选项占用更少的空间。有关 SortedDictionary msdn.microsoft.com/en-us/library/f7fta44c.aspx 的特征列表,请参阅文档的备注部分
【解决方案2】:

它完全取决于 SortedDictionary 类的实现,与 .net 运行时或 CLR 无关。您可以实现自己的排序字典并控制分配的内容和数量。可能 SortedDictionary 实现在内存分配方面效率不高。

【讨论】:

    猜你喜欢
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多