Cluster member variables declaration by their type useful or not?
<p>Please have a look a the following code sample, executed on a Windows-32 system using Visual Studio 2010:</p>

<pre><code>#include &lt;iostream&gt;

using namespace std;

class LogicallyClustered
{
    bool _fA;
    int _nA;
    char _cA;

    bool _fB;
    int _nB;
    char _cB;
};

class TypeClustered
{
    bool _fA;
    bool _fB;

    char _cA;
    char _cB;

    int _nA;
    int _nB;
};

int main(int argc, char* argv[])
{
    cout &lt;&lt; sizeof(LogicallyClustered) &lt;&lt; endl; // 20
    cout &lt;&lt; sizeof(TypeClustered) &lt;&lt; endl; // 12

    return 0;
}
</code></pre>

<hr>

<h1>Question 1</h1>

<p>The <code>sizeof</code> the two classes varies because the compiler is inserting padding bytes to achieve an optimized memory allignment of the variables. Is this correct?</p>

<h1>Question 2</h1>

<p>Why is the memory footprint smaller if I cluster the variables by type as in <code>class TypeClustered</code>?</p>

<h1>Question 3</h1>

<p>Is it a good rule of thumb to always cluster member variables according to their type?
Should I also sort them according to their size ascending (bool, char, int, double...)?</p>

<p><strong>EDIT</strong></p>

<h1>Additional Question 4</h1>

<p>A smaller memory footprint will improve data cache efficiency, since more objects can be cached and you avoid full memory accesses into "slow" RAM. So could the ordering and grouping of the member declaration can be considered as a (small) but easy to achieve performance optimization?</p>
