Home > Blogs > 30 C++ Tips in 30 Days: Tip # 2 Optimize Member Layout

30 C++ Tips in 30 Days: Tip # 2 Optimize Member Layout

By  Nov 20, 2007

Topics: Programming, C/C++

You can reduce the size of classes and structs simply by rearranging data members' order.

Consider the following unoptimized class declaration:

struct C
{
 bool a;
 int b;
 bool c;
}; //sizeof (C) equals 12

The cumulative size of C's members is 1+4+1 bytes, and yet the sizeof this class is twice as big. The extra six bytes are wasted as padding bytes which the compiler inserts between after each data member whose size isn't divisible by 4. Thus, three padding bytes are inserted after the member a, and three more padding bytes are appended after c.

You can reduce the layout of this class by declaring all small data members first, and move the larger data members to the end: 

struct Optimized_C
{
 bool a;
 bool c;
 int b;
}; // sizeof (B) equals 8

This time, the compiler inserted only 2 padding bytes after the member c. Because b occupies 4 bytes, it naturally aligns on a word boundary without necessitating additional padding bytes.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.

Other Things You Might Like

Xamarin Unleashed

Xamarin Unleashed