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?
-
What's up with the downvote and no explanation... that hurts mah feelins you know.Brandon Moore– Brandon Moore2012-02-11 03:42:44 +00:00Commented Feb 11, 2012 at 3:42
-
Well, three people countered it, so you should be fine.Zenexer– Zenexer2012-02-11 03:46:27 +00:00Commented Feb 11, 2012 at 3:46
-
@Zenexer All is right in the world again :)Brandon Moore– Brandon Moore2012-02-11 03:47:20 +00:00Commented Feb 11, 2012 at 3:47
4 Answers
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.
1 Comment
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.
7 Comments
bool fields, it would consume 64 bits by default, due to padding. As a struct, it would consume 16 bits. You could also put [StructLayout(LayoutKind.Sequential)] above the class declaration to forcefully disable padding.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.