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


当前回答

下面的代码片段应该返回传递给它的任何对象的字节大小,只要它可以序列化。 我从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;
}

其他回答

我不认为你可以直接得到它,但有一些方法可以间接地找到它。

一种方法是使用GC。方法来测量创建对象之前和之后使用的内存量。这并不完美,但只要控制了应用程序的其余部分,就可以获得感兴趣的信息。

除此之外,您可以使用分析器获取信息,也可以使用分析api在代码中获取信息。但我认为这并不容易使用。

参见找出c#中的对象正在使用多少内存?对于类似的问题。

下面的代码片段应该返回传递给它的任何对象的字节大小,只要它可以序列化。 我从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.

调试模式

负载SOS

并执行dumpheap命令。

非托管对象:

Marshal.SizeOf(object yourObj);

值类型:

瓦尔sizeof(对象)

管理对象:

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