为什么sortedDictionary需要如此大的开销?
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 个。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SortedDictionary
内部使用TreeSet>
。该树使用Node
并且显然它使用节点之间的引用,因此除了每个键和值之外,您还将引用左节点和右节点以及一些附加属性。Node
是一个类,因此每个实例都有引用类型的传统开销。此外,每个节点还存储一个名为IsRed
的布尔值。根据 WinDbg/SOS,单个节点的大小为 64 位,即 48 字节,因此 10000 个节点将至少占用 480000 字节。
Internally
SortedDictionary<TKey, TValue>
usesTreeSet<KeyValuePair<TKey, TValue>>
. The tree usesNode<T>
and obviously it uses references between nodes, so in addition to each key and value you will have references to left and right nodes as well as some additional properties.Node<T>
is a class so each instance has the traditional overhead of a reference type. Furthermore, each node also stores a boolean calledIsRed
.According to WinDbg/SOS the size of a single node on 64 bits in 48 bytes so 10000 of them will take up at least 480000 bytes.
它完全取决于 SortedDictionary 类的实现,与 .net 运行时或 CLR 无关。您可以实现自己的排序字典并控制分配的内容和数量。就内存分配而言,SortedDictionary 实现可能效率不高。
It completely depends on the implementation of SortedDictionary class and nothing to do with the .net runtime or CLR. You can implement your own sorted dictionary and control what and how much is allocated. Probably SortedDictionary implementation is not much efficient in terms of memory allocation.