gpt4 book ai didi

c# - 为什么 sortedDictionary 需要这么多开销?

转载 作者:太空狗 更新时间:2023-10-29 23:03:00 25 4
gpt4 key购买 nike

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。

最佳答案

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

根据 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

关于c# - 为什么 sortedDictionary 需要这么多开销?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5961334/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com