Crunching bytes. Harder.

Been doing some size/layout optimizations again, recently. Cruncher# proves very useful for tracking problems, however it’s not that great when I want to quickly examine the progress. I have to compile/link application again (takes time, especially if modified structure is included from many files) and reload PDB (in case of bigger projects - takes some more time). Luckily, we can force the compiler to do the work for us. It’s possible to configure MSVC to warn about all padding it adds after structure fields. So, when we already identify wasteful types, it’s enough to enable this warning before defining the structure. Simple example:

// MyFatStructure.cpp
#pragma warning(error: 4820)
#include 'MyFatStructure.h'

#pragma warning(disable: 4820)
Now compiler will complain about all the padding it finds in included file (message: ‘bytes’ bytes padding added after construct ‘member_name’). Every time you fix the layout, switch to .cpp and tap Ctrl+F7 (compile file). This way you avoid compiling/linking the whole project, so turnover time is way lower. Remove #pragmas when you’re done, repeat for next type.

Old comments

Liam 2009-09-19 15:12:23

OK I understand what you mean now :)
“I assume you use precompiled headers?”
The source file I tried it upon was in a static library.

admin 2009-09-08 07:20:06

Basically, I mean minimizing padding, as it tends to grow over time (people just add fields at the end without considering it… On average, I shave about 5% of structure size just by changing layout) and then shuffling fields around so that those which are often accessed together are really placed near each other. #pragma pack(1) is not a good option, since it breaks natural alignment.
About your problem - I assume you use precompiled headers?

Liam 2009-09-07 22:49:44

I do understand when you say “size/layout optimisations” would you mind explaining this? I would have thought if it was required for optimisation then moving the most referenced members higher up would reduce cache misses. If on the other hand the structure layout had to match that of a file format for example would it not be easier to pack the struct with the pragma(pack,packing) pragma(pack,1)…?
I tried this, yet I had to add the pragma in the header and not the source for it to work.