1

Possible Duplicate:
Are there performance issues when using pragma pack(1)?

What's the downside of doing pragma pack(1) in C? I have defined some struct data for a communication protocol and I want to turn off any byte alignment so the data is exactly where it should be and I get the actual size of the struct (11 bytes). What's the downside of turning off byte alignment? Is it performance?

Community
  • 1
  • 1
Boon
  • 40,656
  • 60
  • 209
  • 315
  • The upside is that you'll need slightly less memory, the downside is that CPUs generally cannot access unaligned memory, which means it could take 2 or more reads and a couple of bit shifts to get a single integer field. – zneak Jan 20 '13 at 23:09
  • @Peter, I would argue this question is broader in scope. – Boon Jan 20 '13 at 23:11
  • @Boon: That's why I haven't flagged it... yet. :-) – Peter K. Jan 20 '13 at 23:13

3 Answers3

4

Performance will be slower.

Instead of integers (and other data types) being on 'even' memory boundaries were they can be accessed easily, they may 'straddle' memory boundaries and require TWO fetches (CPU cycles) to retrieve them.

Steve Wellens
  • 20,506
  • 2
  • 28
  • 69
4

There are several "downsides":

  1. It's not C. It's an implementation-specific hack in some C compilers.

  2. It does not really help you with the issue of sending binary structures over the wire or storing them to disk, because you still have byte order issues to deal with.

  3. If st.foo is an int member of a packed structure, &st.foo is not, in general, a valid int *. Passing &st.foo to a function that takes an argument of type int * may cause crashes or memory corruption when the called function attempts to access data through the pointer.

  4. It's gratuitous. A properly-designed structure for binary interchange already has zero padding, because all fields are aligned on boundaries corresponding to their size.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
2

Yes. Due to the nature of the processor/memory connection, accessing multibyte values at an aligned address is significantly faster, and if I remember correctly alignment can also affect caching.

If you will be using the data in the structure for a significant amount of computation, I would recommend working with an unpacked version in code, and converting to a packed version when transmitting. On the other hand, if you aren't doing much computation using the values in the structure, this conversion will be wasteful.

John Colanduoni
  • 1,596
  • 14
  • 18