C# 能否获取一个对象所占内存的大小?
今日,在项目重构的时候忽然想到一个问题,一个类哪些成员的增加,会影响一个类所占内存的大小?C#有没有办法知道一个对象占多少内存呢?
第一个问题:很快想到是类的非静态的字段、属性。
第二个问题:首先想到的是sizeof()。
下面开始验证,首先来验证值类型,验证代码如下:
int size = sizeof (int); //4个字节
注意点:sizeof 运算符仅适用于值类型,而不适用于引用类型。sizeof 运算符只能在不安全代码块中使用。如下面的代码将无法编译通过:
public struct TestStuct
{ } int size = sizeof(new TestStuct());
编译后,提示:
错误 1 “ConsoleApplication3.TestStuct”没有预定义的大小,因此 sizeof 只能在不安全的上下文中使用(请考虑使用 System.Runtime.InteropServices.Marshal.SizeOf)
修改为Marshal.SizeOf方法,改方法返回对象的非托管大小(以字节为单位)。参数可以是引用类型或装箱的值类型。布局必须是连续的或显式的。
int size = Marshal.SizeOf(new TestStuct()); //1个字节
接下来来验证引用类型:
由于不能作为非托管结构进行封送处理;无法计算有意义的大小或偏移量。所有下面的代码在运行的时候,会抛出异常。
public class Student
{
} int size = Marshal.SizeOf(new Student());
需要给Student类,加上一个StructLayoutAttribute,来控制Student类的数据字段的物理布局。修改代码为:
[StructLayout(LayoutKind.Sequential)]
public class Student
{
} int size = Marshal.SizeOf(new Student()); //1个字节
LayoutKind 默认值为Auto.
结论:
1:对于托管对象是没有办法直接获取到一个对象所占的内存大小。
2:非托管对象,可以使用Marshal.SizeOf
3:对内置类型,如int,long,byte等使用sizeof
扩展:
有人提出使用二进制序列化,将一个对象序列化成一个MemoryStream,然后返回MemoryStream.Length,经过验证是不可以的。
验证代码如下:

[Serializable]
public class Student
{
} private static long GetObjectSize(object o)
{
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, o);
using (var fileStream = new FileStream(@"D:\Student.txt", FileMode.OpenOrCreate, FileAccess.Write))
{
var buffer = stream.ToArray();
fileStream.Write(buffer, 0, buffer.Length);
fileStream.Flush();
} return stream.Length;
}
} var student = new Student();
long size = GetObjectSize(student); //139个字节

Student.txt保存的文本信息如下所示,通过文本信息,可以得知多出来的100多个字节,估计是就是这一串字符串吧。
JConsoleApplication3, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null ConsoleApplication3.Student
延伸阅读:
http://blogs.msdn.com/b/cbrumme/archive/2003/04/15/51326.aspx 原文如下:
We don't expose the managed size of objects because we want to reserve the ability to change the way we lay these things out. For example, on some systems we might align and pack differently. For this to happen, you need to specify tdAutoLayout for the layout mask of your ValueType or Class. If you specify tdExplicitLayout or tdSequentialLayout, the CLR’s freedom to optimize your layout is constrained.
If you are curious to know how big an object happens to be, there are a variety of ways to discover this. You can look in the debugger. For example, Strike or SOS (son-of-strike) shows you how objects are laid out. Or you could allocate two objects and then use unverifiable operations to subtract the addresses. 99.9% of the time, the two objects will be adjacent. You can also use a managed profiler to get a sense of how much memory is consumed by instances of a particular type.
But we don't want to provide an API, because then you could form a dependency over this implementation detail.
Some people have confused the System.Runtime.InteropServices.Marshal.SizeOf() service with this API. However, Marshal.SizeOf reveals the size of an object after it has been marshaled. In other words, it yields the size of the object when converted to an unmanaged representation. These sizes will certainly differ if the CLR’s loader has re-ordered small fields so they can be packed together on a tdAutoLayout type.
#5楼 2013-05-16 20:50 AlexanderYao
#7楼 2013-05-16 23:58 jintianzhang
出处:http://www.cnblogs.com/supperwu/archive/2013/05/16/3082061.html
C# 能否获取一个对象所占内存的大小?的更多相关文章
- 如何计算Java对象所占内存的大小
[ 简单总结: 随便一个java项目,引入jar包: lucene-core-4.0.0.jar 如果是 maven项目,直接用如下依赖: <dependency> <groupId ...
- 复杂Java对象所占内存的大小
我们在Java单个对象内存布局中讲解了单个简单的Java对象所占内存的大小的计算.那么这篇文章主要是讲解复杂Java对象所占内存大小的计算,我们把继承.复合的对象称为复杂对象 继承对象 class P ...
- java中基本类型封装对象所占内存的大小(转)
这是一个程序,java中没有现成的sizeof的实现,原因主要是java中的基本数据类型的大小都是固定的,所以看上去没有必要用sizeof这个关键字. 实现的想法是这样的:java.lang.Runt ...
- Android - 获取SD卡的内存空间大小
获取SD卡的内存空间大小 //获得SD卡空间的信息 File path=Environment.getExternalStorageDirectory(); StatFs statFs=new Sta ...
- C++中一个类(非继承类)对象,所占内存空间大小
离职后在家里带了半年多了,这半年多里没有编写过一行代码,倒是看过一些书,但是差不多也都是囫圃吞枣.房子也快要装修,也得赶快找一个工作了,不然养车,还要玩摄影,没收入的日子真是不好过啊.呵呵. 按惯例, ...
- Java学习日记-2.3 基本数据类型和对象所占内存空间大小
转自:http://www.newsmth.net/nForum/#!article/Java/324167
- java如何获取一个对象的大小
When---什么时候需要知道对象的内存大小 在内存足够用的情况下我们是不需要考虑java中一个对象所占内存大小的.但当一个系统的内存有限,或者某块程序代码允许使用的内存大小有限制,又或者设计一个缓存 ...
- java如何获取一个对象的大小【转】
When---什么时候需要知道对象的内存大小 在内存足够用的情况下我们是不需要考虑java中一个对象所占内存大小的.但当一个系统的内存有限,或者某块程序代码允许使用的内存大小有限制,又或者设计一个缓存 ...
- C++中的类所占内存空间总结(转)
类所占内存的大小是由成员变量(静态变量除外)决定的,成员函数(这是笼统的说,后面会细说)是不计算在内的. 摘抄部分: 成员函数还是以一般的函数一样的存在.a.fun()是通过fun(a.this)来调 ...
随机推荐
- QML事件处理 八
1.MouseArea MouseArea 是一个不可见的项目,通常用来和一个可见的项目配合使用来为其提供鼠标处理.鼠标处理的逻辑可以包含在一个MouseArea项目中. MouseArea的enab ...
- Spring MVC同一方法返回JSON/XML格式
最近一道面试题,要求同一API接口支持不同格式返回值.一开始是设想通过过滤器(Filter)设置返回值,但是并不可行,因为方法返回值一般都是类型需要做转换,而过滤器则是前置的.另一方面可以通过拦截器的 ...
- 【读书笔记】Junit实战
Junit实战读书笔记 第一章节 探索Junit: Junit是1997年Erich Gammay和Kent Beck一同创建的一个简单有效的测试框架,其中Erich Gammay是经典<设计模 ...
- Lucene 基础知识
1. 数据分类 结构化数据: 指具有固定格式或有限长度的数据,如数据库等; 非结构化数据: 指不定长或无固定格式的数据, 如邮件,word 文档等磁盘上的文件; 1.1 非结构化数据查询方法 顺序扫描 ...
- luogu P1192 台阶问题
https://www.luogu.org/problem/show?pid=1192 登楼梯 肯定能想到 dp[i] = dp[i-1] + dp[i-2] + ...+ dp[i-k] 然后想到 ...
- Bitmap 位图
转自: http://dongxicheng.org/structure/bitmap/ 1. 概述 位图(bitmap)是一种非常常用的结构,在索引,数据压缩等方面有广泛应用.本文介绍了位图的实现 ...
- python 列表嵌套
>>> a = ['a', 'b', 'c'] >>> n = [, , ] >>> x = [a, n] >>> x [[, ...
- 递归--练习11--noi9273 PKU2506Tiling
递归--练习11--noi9273 PKU2506Tiling 一.心得 25 a[i]%=10;(高精度时) 26 这里错了,花了好久改好 27 28 29 int* f(int n){ 30 if ...
- 理解 Git 的基本概念 ( Merging Collaborating Rebasing)
合并 Merging 在分支上开发新功能后,如何把新功能加入到主分支,让其它人得到你的修改呢?你需要使用命令 git merge 或 git pull. 这两个命令的语法如下: git merge [ ...
- 加载样式js
var MaskUtil = (function(){ var $mask,$maskMsg; var defMsg = '数据导出中,请稍待...'; function init(){ if(!$m ...