quote:
Your five byte struct would get expanded to twelve bytes by the compiler by default. Each field is aligned to a four-byte boundary.
Actually, the original 5 byte structure would be padded out to 8 bytes as follows:
unsigned char m_cHeight;
char padding;
char padding;
char padding;
unsigned short m_iType;
short m_iZLevel;
You can shuffle the data around, but you can''t beat the 8 byte size for these 3 fields. Another option would be to separate the 1byte Height from the 2+2 bytes for Type+ZLevel, so that they would pack better.
The best path would be squeeze the data down to 4 bytes (using bitfields perhaps), so that it packs nicely.
quote:
This to allow more efficient access to the fields.
Actually, compilers try to pad structures so that fields fall on natural bounds for the data type.
Long: padded to start on 4 byte boundary
Short: padded to start on 2 byte boundary
Char: no padding
Array: padded to start/end on 4 byte boundary
Struct: padded to start/end on 4 byte boundary
It''s often faster to read a 2 or 4 byte word when it falls on a 2 or 4 byte boundary, respectively. In addition, reading 2 or 4 byte words from an odd address can cause a hardware exception on certain processors.
Note that the actual padding is compiler dependent, since the ANSI C standard doesn''t specify if or how it should be implemented, but the behavior above is standard in all of the compilers I''ve examined.
quote:
You could pack the structs, in which case your struct would only take five bytes, but it will not be as fast to access by the processor because it will have to access multiple DWORDs and do byte shifting to get the field it wants.
For data stored on disk, packing is a practical balance between speed and footprint. At worst, read the file into memory as a single chunk, then expand the tiles to a (padded) data structure.
As far as speed, you are only talking 1 extra cycle for a read or write misaligned data. Since we are using tiles that will be accessed sparsely and infrequently (as opposed to pixels in an offscreen buffer), the overhead would be negligible compared to the simplicity of design.