Our headers use #pragma pack(1) around most of our structs (used for net and file I/O). I understand that it changes the alignment of structs from the default of 8 bytes, to an alignment of 1 byte.
Assuming that everything is run in 32-bit Linux (perhaps Windows too), is there any performance hit that comes from this packing alignment?
I’m not concerned about portability for libraries, but more with compatibility of file and network I/O with different #pragma packs, and performance issues.
Memory access is fastest when it can take place at word-aligned memory addresses. The simplest example is the following struct (which @Didier also used):
By default, GCC inserts padding, so a is at offset 0, and b is at offset 4 (word-aligned). Without padding, b isn’t word-aligned, and access is slower.
How much slower?
As with most performance questions, you’d have to benchmark your application to see how much of an issue this is in practice.
Regarding portability: I assume that you’re using
#pragma pack(1)so that you can send structs across the wire and to and from disk without worrying about different compilers or platforms packing structs differently. This is valid, however, there are a couple of issues to keep in mind: