c++compiler-optimizationmemory-optimization

Can I force a C++ class to compile using the minimum amount of space?


I have a class that I will literally instantiate billions of. I did my best to put as little data as possible in it, and I got it down to 10 bytes when compiled for an x64 architecture: an unsigned short int and a size_t. When I mouse over sizeof(myclass) (in VS), however, it reports 16 bytes. If I comment out either of the fields, the size of the class is what you'd expect, 10 bytes and 2 bytes respectively.

Is there a way to instruct the compiler to use only 10 bytes for my class?


Solution

  • #pragma pack can make your structures smaller. On the other hand, it can make retrieving the member data slower, since the alignment of the bytes is not guaranteed. As a result the compiler will need extra instructions to fetch the data from different memory locations. For more info, this link has an excellent post: #pragma pack effect