我需要知道我的对象在内存中消耗多少字节(在c#中)。例如我的哈希表,或SortedList,或List<String>。
非托管对象:
Marshal.SizeOf(object yourObj);
值类型:
瓦尔sizeof(对象)
管理对象:
看起来没有直接的方法来获取托管对象,参考: https://learn.microsoft.com/en-us/archive/blogs/cbrumme/size-of-a-managed-object
我不认为你可以直接得到它,但有一些方法可以间接地找到它。
一种方法是使用GC。方法来测量创建对象之前和之后使用的内存量。这并不完美,但只要控制了应用程序的其余部分,就可以获得感兴趣的信息。
除此之外,您可以使用分析器获取信息,也可以使用分析api在代码中获取信息。但我认为这并不容易使用。
参见找出c#中的对象正在使用多少内存?对于类似的问题。
这可能不准确,但对我来说已经足够接近了
long size = 0;
object o = new object();
using (Stream s = new MemoryStream()) {
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(s, o);
size = s.Length;
}
下面的代码片段应该返回传递给它的任何对象的字节大小,只要它可以序列化。 我从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.
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 确定记录是否存在的最快方法
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 阅读GHC核心
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- Python: List vs Dict用于查找表
- c#和Java中的泛型有什么不同?和模板在c++ ?