44

Does alignment really matter for performance in C++11?

There is an advice in Stroustrup's book to order the members in a struct beginning from the biggest to the smallest. But I wonder if someone has made measurements to actually see if this makes any difference, and if it is worth it to think about when writing code.

7
  • 12
    "But I wonder if someone has made measurements to actually see if this makes any difference," - you could do that and report back.... Commented Dec 28, 2013 at 0:40
  • 6
    @MitchWheat If I knew how I would not have asked. Commented Dec 28, 2013 at 0:44
  • 3
    you write some code with a struct aligned one way and then the other and you access it in a loop for say a million iterations and you time it. Pretty simple program. Commented Dec 28, 2013 at 0:45
  • 5
    It really depends on architecture. Some processors are simply unable to handle unaligned data, and as a result, require arithmetic at the software level to split an integer over an alignment boundary, which is obviously going to waste cycles.
    – Mark H
    Commented Dec 28, 2013 at 0:46
  • 4
    If you cannot measure a performance difference, why would it matter to you? Commented Dec 28, 2013 at 1:13

2 Answers 2

98

Alignment matters not only for performance, but also for correctness. Some architectures will fail with an processor trap if the data is not aligned correctly, or access the wrong memory location. On others, access to unaligned variables is broken into multiple accesses and bitshifts (often inside the hardware, sometimes by OS trap handler), losing atomicity.

The advice to sort members in descending order of size is for optimal packing / minimum space wasted by padding, not for alignment or speed. Members will be correctly aligned no matter what order you list them in, unless you request non-conformant layout using specialized pragmas (i.e. the non-portable #pragma pack) or keywords. Although total structure size is affected by padding and also affects speed, often there is another ordering that is optimal.

For best performance, you should try to get members which are used together into the same cache line, and members that are accessed by different threads into different cache lines. Sometimes that means a lot of padding to get a cross-thread shared variable alone in its own cache line. But that's better than taking a performance hit from false sharing.

15
  • 2
    This is a top-notch answer Commented Dec 28, 2013 at 0:51
  • 1
    "but also for correctness" It's not possible to order data members in a class such that the members are illegally aligned; such illegally aligned accesses are a separate issue generally arising from aliasing violations rather than member ordering.
    – bames53
    Commented Dec 28, 2013 at 0:52
  • 1
    @bames53: I was just editing to clarify that. It is possible, but only with non-standard compiler-specific packing pragmas.
    – Ben Voigt
    Commented Dec 28, 2013 at 0:53
  • 3
    Perhaps it would be beneficial to explain why sorting helps: the compiler will respect alignment rules, but also has to respect member order. If you sort by size, the compiler needs to insert less padding. This is because sorting by size in practice amounts to sorting by alignment restrictions (which is what you actually should do - a char[53] should go last)
    – MSalters
    Commented Dec 28, 2013 at 1:45
  • 1
    @user1911091: I didn't watch to see what the claim was, but pragma pack still affects correctness. You can't use unaligned variables with most SSE instructions. You can't use unaligned addresses with interlocked instructions (x86 LOCK prefix). Speed considerations are secondary to having the program work.
    – Ben Voigt
    Commented Jul 29, 2019 at 13:12
11

Just to add to Ben's great answer:

Defining struct members in the same order they are later accessed in your application will reduce cache misses and possibly increase performance. This will work provided the entire structure does not fit into L1 cache.

On the other hand, ordering the members from biggest to smallest may reduce overall memory usage, which may be important when storing an array of small structures.

Let's assume that for an architecture (I don't know them that well, I think that would be the case for default settings 32bit gcc, someone will correct me in comments) this structure:

struct MemoryUnused {
  uint8_t val0;
  uint16_t val1;
  uint8_t val2;
  uint16_t val3;
  uint8_t val4;
  uint32_t val5;
  uint8_t val6;
}

takes 20 bytes in memory, while this:

struct MemoryNotLost {
  uint32_t val5;
  uint16_t val1;
  uint16_t val3;
  uint8_t val0;
  uint8_t val2;
  uint8_t val4;
  uint8_t val6;
}

Will take 12. That's 8 bytes lost due to padding, and it's a 67% increase in size of the smallers struct. With a large array of such structs, the gain would be significant and, simply because of the amount of used memory, will decrease the amount of cache misses.

9
  • 1
    While you have a theoretical point, your argument seems pretty mute in all circumstances I know about: First, only very few structs are always accessed in the same order. Second, a struct that does not fit into level 1 cache is a veritable monster and should never be produced. Third, we frequently have many small objects in large arrays, and here only one thing matters for performance: the overall size of the objects. And fourth, we should not have unrelated parts within a single structure anyway, that is against the spirit of object orientation. Commented Jan 2, 2014 at 12:18
  • 2
    @cmaster First, the question is theoretical. Second, we use multiple char[] in a struct to store user input data in frontend - we may not be proud of it, but that's the case. Pointers to multiple long strings would be as bad. Third - that's the point, overall size may be reduced with ordering. Fourth - I do not understand what you're addressing here. Certainly not my post.
    – Dariusz
    Commented Jan 2, 2014 at 12:22
  • 1
    @cmaster: Quite the contrary... whenever you compose objects to make a larger object, you have operations (the subobject behaviors) that access only a subset of the complete object. That's not "against the spirit of OO", that's normal.
    – Ben Voigt
    Commented Jan 2, 2014 at 17:02
  • And your conclusion is wrong. If there is a large array of such structs and there exists some loop that uses the int32_t member (whose name strangely changed from val5 to val0) and the int8_t val6 member, the latter memory layout will cause twice as many cache misses as the former (padded) one. There probably exists a packed layout that doesn't suffer this problem, but simple size sorting isn't it.
    – Ben Voigt
    Commented Jan 2, 2014 at 17:06
  • 1
    @BenVoigt I changed the names. I didn't think they were meaningful, but now I realize they can be confusing. Thanks for the note. Does your last note still apply? If so, please elaborate, since I am not certain I understand it.
    – Dariusz
    Commented Jan 2, 2014 at 17:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.