我需要知道我的对象在内存中消耗多少字节(在c#中)。例如我的哈希表,或SortedList,或List<String>。


当前回答

调试模式

负载SOS

并执行dumpheap命令。

其他回答

调试模式

负载SOS

并执行dumpheap命令。

这可能不准确,但对我来说已经足够接近了

long size = 0;
object o = new object();
using (Stream s = new MemoryStream()) {
    BinaryFormatter formatter = new BinaryFormatter();
    formatter.Serialize(s, o);
    size = s.Length;
}

非托管对象:

Marshal.SizeOf(object yourObj);

值类型:

瓦尔sizeof(对象)

管理对象:

看起来没有直接的方法来获取托管对象,参考: https://learn.microsoft.com/en-us/archive/blogs/cbrumme/size-of-a-managed-object

下面的代码片段应该返回传递给它的任何对象的字节大小,只要它可以序列化。 我从Quixant的一位同事那里得到这个工具,以解决在游戏平台上写入SRAM的问题。希望能有所帮助。 感谢卡洛·维图奇。

/// <summary>
/// Calculates the lenght in bytes of an object 
/// and returns the size 
/// </summary>
/// <param name="TestObject"></param>
/// <returns></returns>
private int GetObjectSize(object TestObject)
{
    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    byte[] Array;
    bf.Serialize(ms, TestObject);
    Array = ms.ToArray();
    return Array.Length;
}

好了,这个问题已经回答了,答案已经被接受了,但是有人让我把我的答案放上去。

首先,这是不可能确定的。它是一个内部实现细节,没有文档化。但是,根据对象所包含的其他对象。现在,我们如何计算缓存对象的内存需求呢?

我之前在这篇文章中提到过这个主题:

Now, how do we calculate the memory requirement for our cached objects? Well, as most of you would know, Int32 and float are four bytes, double and DateTime 8 bytes, char is actually two bytes (not one byte), and so on. String is a bit more complex, 2*(n+1), where n is the length of the string. For objects, it will depend on their members: just sum up the memory requirement of all its members, remembering all object references are simply 4 byte pointers on a 32 bit box. Now, this is actually not quite true, we have not taken care of the overhead of each object in the heap. I am not sure if you need to be concerned about this, but I suppose, if you will be using lots of small objects, you would have to take the overhead into consideration. Each heap object costs as much as its primitive types, plus four bytes for object references (on a 32 bit machine, although BizTalk runs 32 bit on 64 bit machines as well), plus 4 bytes for the type object pointer, and I think 4 bytes for the sync block index. Why is this additional overhead important? Well, let’s imagine we have a class with two Int32 members; in this case, the memory requirement is 16 bytes and not 8.