Brandon Moore
Brandon Moore

Reputation: 8790

Size of objects in memory

If I have a class with 100 properties that are all int32's, and I have instanced 100 of these objects then does it necessarily take up 40000 bytes (plus whatever other overhead an object takes) even before any of the properties are set or does some (or all) of that space remain unallocated until you actually assign a value to the preoperties for the first time?

Upvotes: 1

Views: 172

Answers (4)

Zenexer
Zenexer

Reputation: 19611

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.

Upvotes: 1

Andrew Barber
Andrew Barber

Reputation: 40160

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.

Upvotes: 1

Joel Coehoorn
Joel Coehoorn

Reputation: 416149

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.

Upvotes: 2

dtb
dtb

Reputation: 217401

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.

Upvotes: 2

Related Questions