简体   繁体   中英

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.

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). As you start setting values to the strings, then you would start using the space.

Int32 , like all value types, has a default value. (0)

So yes; as soon as you create those Int32 variables, they are taking up memory.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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