Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing memory layout of class instances in C++

Upgrading an application from 32 to 64 bit increases the pointer size and the memory footprint of objects.

I am looking for methods to reduce the memory footprint of objects as much as possible. For POD structs I dump the memory layout of the structure to figure out how to pack the members and reduce compiler padding.

Is there a way to figure out the memory layout of non-POD objects such as class instances? How could I achieve something similar to packing of class objects?

Thanks, Dan

like image 733
dbbd Avatar asked Apr 03 '12 07:04

dbbd


2 Answers

You can use GCC's -Wpadded to inform you where padding is added, then reorder based on that information, reducing the size in some cases.

Force-Packing the data is not a good idea for representations in memory.

like image 128
justin Avatar answered Nov 16 '22 12:11

justin


I do not know about specific non-POD objects data (i.e. vtable), even though I suppose that is dictated by the pointer size. Anyway, you can control the alignment of members with the compiler directive #pragma pack that is supported both by GCC and Visual Studio.

You can also read paragraph 7.18 on wonderful Agner Fog C++ optimize guide:

The data members of a class or structure are stored consecutively in the order in which they are declared whenever an instance of the class or structure is created. There is no performance penalty for organizing data into classes or structures. Accessing a data member of a class or structure object takes no more time than accessing a simple variable. Most compilers will align data members to round addresses in order to optimize access

like image 1
Luca Martini Avatar answered Nov 16 '22 12:11

Luca Martini