I have a structure I would like to optimize the footprint of.
typedef struct dbentry_s {
struct dbentry_s* t_next;
struct dbentry_s* a_next;
char *t;
char *a;
unsigned char feild_m;
unsigned char feild_s;
unsigned char feild_other;
} dbentry;
As I understand it, the compiler creates structures in memory as you define them. So larger types should be declared first so the small types can fill in the alignment holes.
I have read the WikiPedia article on data structure alignment and other articles on the issue. http://en.wikipedia.org/wiki/Data_structure_alignment
But I'm still not sure, is my current ordering the most optimal or am I mi开发者_开发知识库ssing something?
Note: My compiler doesn't support "#pragma pack"
No, that should be the most optimal order based on common compiler behavior (keeping in mind that the standard does not actually mandate how the structures are packed with respect to the spaces between the elements, although it does guarantee the order is as specified: see '6.2.5 Types' of the latest draft C1x-n1425).
You have all your pointers up the front and all your characters down the back, so you'll probably find that, with a four-byte pointer size you'll end up with a 19- or 20-byte structure.
You can easily check this by inserting the following lines in your code:
printf ("Size of dbentry* is %d\n", sizeof (struct dbentry_s*));
printf ("Size of char* is %d\n", sizeof (char*));
printf ("Size of uns char is %d\n", sizeof (unsigned char));
printf ("Size of stucture is %d\n", sizeof (dbentry));
The reason I've put in all the sizeof
checks is to ensure you have full information. I'm well aware the sizeof(char)
is always 1.
You might be interested in using pahole and/or Cruncher#. Both are tools that analyze the layout of structures in memory.
Reference: original Maciej Sinilo blog post about Cruncher#.
精彩评论