none
Float and bool consume 16 bytes RRS feed

  • Question

  • Hi,

    I am finishing my application and trying to tune it a bit now. All is going well, I am using Red Gate ANTS memory profiler. 

    I experience a weird problem or maybe I just am just missing something. I have an pretty big array of classes, so I try to keep the size of this class as low as possible. It is pretty much only a container for data with one float and one bool.

    One would expect that the total consumption of one class instance is 5 bytes (4 for float and 1 for bool), however ANTS memory profiler says something different. It actually consumes 16 bytes. This is a bad news, because it means cca 10MB higher memory usage.

    Can someone please explain me why is this happening?

    Thank you.

    Sunday, December 29, 2013 6:41 PM

Answers

  • Class comes with overhead. How is object.GetType supposed to work if you don't embed a method table pointer in the class? Also you need a Syncblock to have the lock keyword working.

    If you want to reduce the memory footprint, use a structure with StructLayout(LayoutKind.Sequential) and StructLayout.Pack.




    Visual C++ MVP

    • Marked as answer by Pavel Ku Tuesday, December 31, 2013 8:20 AM
    Sunday, December 29, 2013 7:12 PM

All replies

  • Class comes with overhead. How is object.GetType supposed to work if you don't embed a method table pointer in the class? Also you need a Syncblock to have the lock keyword working.

    If you want to reduce the memory footprint, use a structure with StructLayout(LayoutKind.Sequential) and StructLayout.Pack.




    Visual C++ MVP

    • Marked as answer by Pavel Ku Tuesday, December 31, 2013 8:20 AM
    Sunday, December 29, 2013 7:12 PM
  • Hi Sheng,

    thank you very much for pointing me in the right direction. 

    8 bytes is the "class overhead" - sync block (4 bytes) and type (4 bytes)

    4 bytes is my float

    1 byte is my bool (however it is rounded to 4 bytes because of the 32bit architecture). 

    Is that correct?

    Monday, December 30, 2013 1:02 PM
  • If memory efficiency is your concern, then use a struct rather than a class, and pack it.

    [StructLayout( LayoutKind.Sequential, Pack = 1 )]
    struct Foo
    {
        public float a;
        public bool b;
    }
    

    Then create your array of them.  e.g.:

    Foo[] myArray = new Foo[10000000];


    Monday, December 30, 2013 2:23 PM
  • Hi Wyck,

    thank you for reply. I will definitely go with structs. I would just like to know if it works as I written above.

    Monday, December 30, 2013 2:32 PM