Sunday, March 3, 2019

c++ - Cluster member variables declaration by their type useful or not?




Please have a look a the following code sample, executed on a Windows-32 system using Visual Studio 2010:



#include 

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 << sizeof(LogicallyClustered) << endl; // 20
cout << sizeof(TypeClustered) << endl; // 12

return 0;
}








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





Why is the memory footprint smaller if I cluster the variables by type as in class TypeClustered?






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...)?



EDIT





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?


Answer




1) Absolutely correct.



2) It's not smaller because they are grouped, but because of the way they are ordered and grouped. For example, if you declare 4 chars one after the other, they can be packed into 4 byte. If you declare one char and immediately one int, 3 padding bytes will be inserted as the int will need to be aligned to 4 bytes.



3) No! You should group members in a class so that the class becomes more readable.



Important note: this is all platform/compiler specific. Don't take it ad-literam.



Another note - there also exist some small performance increase on some platforms for accessing members that reside in the first n (varies) bytes of a class instance. So declaring frequently accessed members at the beginning of a class can result in a small speed increase. However, this too shouldn't be a criteria. I'm just stating a fact, but in no way recommend you do this.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...