Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Optimizing Class Member Alignment (http://www.go4expert.com/articles/optimizing-class-alignment-t858/)

pradeep 2Jun2006 14:17

Optimizing Class Member Alignment
 
The size of a class can be changed simply by playing with the order of its members' declaration:

Code: CPP

struct A
 {
 bool a;
 int b;
 bool c;
 }; /*sizeof (A) == 12*/


On my machine, sizeof (A) equals 12. This result might seem surprising because the total size of A's members is only 6 bytes: 1+4+1 bytes. Where did the remaining 6 bytes come from? The compiler inserted 3 padding bytes after each bool member to make it align on a four-byte boundary. You can reduce A's size by reorganizing its data members as follows:

Code: CPP

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


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

shabbir 2Jun2006 16:24

Re: Optimizing Class Member Alignment
 
A theory similar to this thread.

I guess its always possible on optimizing grounds if you are a bit more careful

aisha.ansari84 5Mar2008 18:44

Re: Optimizing Class Member Alignment
 
optimization is not so necessary but efficient programming is


All times are GMT +5.5. The time now is 02:34.