2011-05-11 48 views
5
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位):为什么sortedDictionary需要这么多开销?

280108 

输出(64位):

480248 

单独(在阵列)存放整数需要大约80000

+0

欢迎来到.NET运行时。 – 2011-05-11 08:33:57

+0

,因为它是一棵树。还有SortedList和一个普通的列表,它们恰好被排序(确保将项目插入到适当的位置) – harold 2011-09-28 09:27:39

回答

5

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

根据WinDbg/SOS,48个字节中的64位单节点的大小,因此它们中的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 
+0

它是否真的需要这个开销来支持它的功能? – willem 2011-05-11 09:49:19

+1

@Willem:我想真正的问题是;你需要SortedDictionary的所有功能吗?如果没有,那么占用较少空间的选项。请参阅文档的“备注”部分以获取SortedDictionary的特性列表http://msdn.microsoft.com/en-us/library/f7fta44c.aspx – 2011-05-11 11:04:26

2

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