简体   繁体   English

内存中对象的大小

[英]Size of objects in memory

如果我有一个具有100个都是int32的属性的类,并且已经实例化了100个这些对象,那么即使在设置任何属性之前还是执行某些操作(或全部)保留该空间,直到您第一次真正为前置操作分配值之前?

When an object is created, the memory for all fields is allocated immediately. 创建对象时,将立即分配所有字段的内存。 Note that the size of the object also includes the object header, padding, etc. 请注意,对象的大小还包括对象标头,填充等。

You use the memory as soon as you instantiate the object, because int is a value type. 实例化对象后立即使用内存,因为int是一种值类型。

Reference types work a little different. 引用类型的工作有点不同。 If you were to make the property strings instead of integers, you would still use the ~40,000 bytes, but no more, because at this point your strings are all null-references (null references still reserve the space for the reference). 如果要使用属性字符串而不是整数,则仍将使用〜40,000字节,但不能再使用更多字节,因为此时您的字符串都是空引用(空引用仍为引用保留空间)。 As you start setting values to the strings, then you would start using the space. 开始为字符串设置值时,您将开始使用空格。

Int32 , like all value types, has a default value. 像所有值类型一样, Int32具有默认值。 (0) (0)

So yes; 是的 as soon as you create those Int32 variables, they are taking up memory. 一旦创建了这些Int32变量,它们就会占用内存。

All class-scoped fields are "assigned" following instantiation, unlike locally-scoped variables, which can remain unassigned indefinitely. 实例化后,所有类作用域字段都是“分配的”,这与局部作用域变量不同,后者可以无限期保持未分配状态。 Thus, value types consume their appropriate size, and references consume the size of a moving pointer, no matter what--when they are scoped at the class level. 因此,值类型消耗它们的适当大小,而引用则消耗移动指针的大小,无论它们是什么(当它们在类级别作用域时)。

Note also that unless the layout is sequential (as in a struct) or explicit, most value types will be padded to at least 32 bits. 还要注意,除非布局是顺序的(如在结构中)或显式的,否则大多数值类型将被填充为至少32位。

It's not always straightforward to predict how much space a null reference will consume, but were they normal pointers, they would consume 4 bytes on x86 platforms and 8 bytes on x64 platforms. 预测空引用将消耗多少空间并不总是那么简单,但是如果它们是普通指针,则在x86平台上将消耗4个字节,在x64平台上将消耗8个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM