1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Optimizing Class Member Alignment

Discussion in 'C++' started by pradeep, Jun 2, 2006.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    The size of a class can be changed simply by playing with the order of its members' declaration:

    Code:
    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:
    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.
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,283
    Likes Received:
    364
    Trophy Points:
    83
    A theory similar to [thread=449]this thread[/thread].

    I guess its always possible on optimizing grounds if you are a bit more careful
     
  3. aisha.ansari84

    aisha.ansari84 New Member

    Joined:
    Feb 13, 2008
    Messages:
    82
    Likes Received:
    1
    Trophy Points:
    0
    optimization is not so necessary but efficient programming is
     

Share This Page