字典对象的大小(单位为字节)

4

我想知道字典项的大小(单位为字节)。我该如何做呢?有没有预定义的方法可以使用?我看到类似的问题被回答说要使用GC.TotalMemory方法来获取差异,但是在这里我无法使用Gc.KeepAlive对象。请给出建议。在使用字典之前和之后计算差异的问题不可行,因为总内存不仅包括该字典的内存,还包括其他几个线程的内存。请提供另一种方法。


你应该提供更多的信息。为什么需要大小?这些对象是否可序列化? - Henrik
我需要知道大小,因为由于高内存消耗,我需要优化代码。为此,我需要知道我的字典是否有效。而且这些对象不可序列化。 - user3164883
1个回答

0
你可以这样做:
long StopBytes = 0;

// Declare your dictionnary
Dictionary<string, int> myDictionary;

// Get total memory before create your dictionnary
long StartBytes = System.GC.GetTotalMemory(true);

// Initialize your dictionnary
myDictionary = new Dictionary<string, int>();

// Get total memory after create your dictionnary
StopBytes = System.GC.GetTotalMemory(true);

// This ensure a reference to object keeps object in memory
GC.KeepAlive(myFoo); 

// Calcul the difference , and that all :-)
MessageBox.Show("Size is " + ((long)(StopBytes - StartBytes)).ToString());

更多信息请点击这里 -> http://blogs.msdn.com/b/mab/archive/2006/04/24/582666.aspx


4
有一个问题。我可以这样做,但是当字典创建并添加项目时,还有许多其他线程同时运行。所以是否有另一种方法,我不必在之前和之后计算总内存?因为总内存将包括除字典内存外的几个其他线程的内存。请给予建议。 - user3164883

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接