添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

今日,在项目重构的时候忽然想到一个问题,一个类哪些成员的增加,会影响一个类所占内存的大小?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.

  • · C#定点任务代码 类似Windows计划任务(健壮性高) (2015-08-11)
  • · C# Xml中SelectSingleNode方法中的xpath用法(Xml节点操作最佳方式) (2015-10-30)
  • · C#对象序列化与反序列化 (2015-10-30)
  • · C# Stream流使用总结 (2015-11-09)
  • · C#位运算符(C#按位与、按位或 等) (2015-12-04)
  • 1 js中int和string互换(js int转string,js string转int)
  • 2 虚拟机安装CentOS出错:EDD:Error 8000 r...
  • 3 chown: invalid user: mysql:mysql
  • 4 路径 /storage/emulated/0/... 在哪儿?
  • 5 Web API 最佳入门指南
  • 6 宽度默认980px?手机浏览器及pc浏览器width...
  • 7 [解决]Windows 成功诊断出虚拟内存不足的情况
  • 8 Mac OS 可视化ssh文件传输工具(替代scp命令行)
  • 9 GIF截图工具, 三款免费好用的Gif截图工具推荐
  • 10 [解决] RHEL 7/ CentOS 7/Fedora 出现...
  • 5 海量数据相似度计算之simhash和海... 2次评论
  • 6 C++使用OLE/COM高速读写EXCEL的源码 2次评论
  • 7 AfxIsValidAddress 测试内存地址 2次评论
  • 8 C++入门进阶最佳实战 2次评论
  • 9 解决xrdp登陆不上的问题:xrdp s... 2次评论
  • 10 VC 自绘日历,有绘制日历需求的... 2次评论
  •