none
Memory allocation when creating a new object RRS feed

  • Question

  • When instantiating a reference type, how does the CLR determine how much memory to reserve?


    Monday, March 23, 2009 7:47 PM

Answers

  • For 32-bit, an object has a fixed overhead of 8 bytes, in addition to the memory needed for the class's member variables.  If the object would otherwise take less than 12 bytes, it is padded to 12 bytes.

    For 64-bit, these numbers double to 16 and 24.

    Note that due to alignment rules, the memory needed for the class's member variables might be greater than just adding together the apparent sizes (such as Int32 = 4 bytes, Int64 = 8 bytes, etc.) of the data types.



    • Marked as answer by Klaus Nji Tuesday, March 24, 2009 3:17 PM
    Monday, March 23, 2009 11:09 PM

All replies

  • For 32-bit, an object has a fixed overhead of 8 bytes, in addition to the memory needed for the class's member variables.  If the object would otherwise take less than 12 bytes, it is padded to 12 bytes.

    For 64-bit, these numbers double to 16 and 24.

    Note that due to alignment rules, the memory needed for the class's member variables might be greater than just adding together the apparent sizes (such as Int32 = 4 bytes, Int64 = 8 bytes, etc.) of the data types.



    • Marked as answer by Klaus Nji Tuesday, March 24, 2009 3:17 PM
    Monday, March 23, 2009 11:09 PM
  • Thanks for the response.  A followup question:

    For member variables with fixed length such as Int32 I can see how the CLR determines how much memory to reserve.  What about member variables with variable length such as strings or arrays?  How does the CLR determine how much memory to reserve in this case?


    Wednesday, March 25, 2009 1:30 PM
  • In the class where they are referenced, it's the size of a reference (32/64bits).
    And then they will have a new allocated object for their contents. I don't know the real size, but I think that a byte array is:

    A reference where it was declared.

    And the real object is:
    The fixed overhead.
    Plus the size of the array. If it's a bytearray, it simple it's size.


    ------------- Paulo Zemek - System Architect
    Thursday, April 2, 2009 12:26 PM