一个好的方法来估算/计算内存对象的大小 [英] A good way to estimate/calculate object size in memory

查看:188
本文介绍了一个好的方法来估算/计算内存对象的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有对象汤姆有类人。

Lets say I have object Tom which has class Person.

Class Person

String Name
DateTime BirthDate
String Role
Int32 Salary

您可以给我它的内存大小近似,如果它具有以下值:

Can you give me an approximation of its memory size if it has the following values:

名称=汤姆。出生日期= 1990年1月1日。角色=用户。工资= 30000

Name = Tom. BirthDate = 1/1/1990. Role = User. Salary = 30000

您也可以给我一些洞察计算是怎么做的?

Could you also give me some insight into how the calculation was done?

推荐答案

要获得真实的数据,使用的 CLR探查。要以编程方式做到这一点,使用 的sizeof (仅适用于值类型)。您也可以通过引用GC直接这样做 ...

To get a true figure, use the CLR profiler. To do it programmatically, use sizeof (only works on value types). You could also do it by referencing the GC directly like this...

long StopBytes = 0;
foo myFoo;

long StartBytes = System.GC.GetTotalMemory(true);
myFoo = new foo();
StopBytes = System.GC.GetTotalMemory(true);
GC.KeepAlive(myFoo); // This ensure a reference to object keeps object in memory

long TotalBytes = StopBytes - StartBytes;
MessageBox.Show("Size is " + TotalBytes.ToString());

这篇关于一个好的方法来估算/计算内存对象的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆