Sub topic 7
Alignment, padding, and field order
This chapter assumes you can read C structs and know that a cache line is the unit the CPU moves between memory and cache, typically 64 bytes. You do not need assembly knowledge. The goal is to predict sizeof for a struct, shrink it by reordering fields, and understand why a smaller struct runs faster in a loop.
Why alignment exists
Most CPUs load a value most efficiently when its address is a multiple of its size. A 4-byte int belongs at an address divisible by 4. An 8-byte double belongs at an address divisible by 8. This rule is called alignment. The alignment requirement of a type is usually equal to its size for scalar types, and you can query it with _Alignof in C11 or alignof in C++.
An aligned value never straddles two cache lines. A misaligned 8-byte load that crosses a line boundary needs two line fetches. Some architectures fault on misaligned access, and others handle it slowly.
The compiler enforces alignment by inserting unused bytes, called padding, between fields and at the end of the struct. You pay for those bytes in memory and in cache space.
The layout rules
For a typical x86-64 ABI, the compiler follows these rules:
- Each field is placed at the next offset that is a multiple of that field's alignment.
- The struct's own alignment equals the largest alignment among its fields.
- The struct's total size is rounded up to a multiple of its own alignment. This tail padding keeps every element of an array correctly aligned.
Applying these rules to the example from the topic plan:
#include <stdio.h>
#include <stddef.h>
/* Poor order: padding is inserted after 'a' and after 'c'. */
struct Wasteful {
char a;
double b;
char c;
};
/* Better order: largest alignment first. */
struct Compact {
double b;
char a;
char c;
};
int main(void) {
printf("Wasteful: size=%zu align=%zu\n",
sizeof(struct Wasteful), _Alignof(struct Wasteful));
printf(" a@%zu b@%zu c@%zu\n",
offsetof(struct Wasteful, a),
offsetof(struct Wasteful, b),
offsetof(struct Wasteful, c));
printf("Compact: size=%zu align=%zu\n",
sizeof(struct Compact), _Alignof(struct Compact));
printf(" b@%zu a@%zu c@%zu\n",
offsetof(struct Compact, b),
offsetof(struct Compact, a),
offsetof(struct Compact, c));
return 0;
}On x86-64 with common ABIs this prints sizes 24 and 16. Wasteful has a at offset 0, 7 bytes of padding, b at 8, c at 16, and 7 bytes of tail padding. Compact has b at 0, a at 8, c at 9, and 6 bytes of tail padding. Both structs hold the same 10 bytes of data, but one wastes 14 bytes and the other wastes 6.
Why this matters for the cache
Struct size decides how many elements fit in a 64-byte line. With 16-byte structs, exactly 4 fit per line and none straddles a boundary. With 24-byte structs, 2.67 fit per line, so some elements span two lines. If you sum a field across an array of one million elements, the 24-byte version moves 24 MB through the cache and the 16-byte version moves 16 MB. That is a third less traffic for no change in logic.
The effect compounds when the working set is near a cache size. A 16 MB array may fit in a large last-level cache while a 24 MB array does not, and the cliff in performance is much larger than the 1.5x size difference.
Straddling matters too. An element at offset 48 in a 24-byte array spans bytes 48 to 71, which crosses the line boundary at 64. Reading it costs two line fetches. Sizes that divide 64 evenly (8, 16, 32, 64) avoid this when the array itself starts on a line boundary.
Reordering fields
The simple rule is to sort fields by descending alignment: pointers and 8-byte values first, then 4-byte values, then 2-byte values, then single bytes. Padding then appears mostly at the end, and it is limited to less than the struct's alignment.
Check your result instead of trusting the rule. A compile-time assertion makes the layout a tested property:
#include <cstdint>
struct Record {
std::uint64_t id;
double score;
std::uint32_t count;
std::uint16_t flags;
std::uint8_t kind;
std::uint8_t level;
};
static_assert(sizeof(Record) == 24, "Record layout changed");
static_assert(alignof(Record) == 8, "Record alignment changed");
int main() {
return 0;
}If someone adds a field in the wrong place, the build fails instead of the benchmark slowly regressing.
Tools can also report padding. pahole (from the dwarves package) prints each struct's holes from debug info, and Clang's -Wpadded warns whenever padding is inserted.
Other ways to shrink a struct
Reordering costs nothing at run time. Other methods trade something for space:
- Use narrower types where the range allows. A
uint32_tindex in place of a pointer orsize_tsaves 4 bytes per field. - Replace several
boolfields with a bit set or bit fields. Bit fields save space but their layout is implementation-defined, and each access costs extra shift and mask instructions. - Move rarely used fields into a separate structure. A later chapter covers this hot and cold splitting.
Gotchas
- Packed structs.
__attribute__((packed))or#pragma pack(1)removes padding, but fields become misaligned. Access may be slower, may fault on some CPUs, and taking a pointer to a packed field can produce undefined behavior. Use packing for wire formats and file layouts, not for hot in-memory data. - ABI differences. Sizes depend on the platform. On 32-bit x86 Linux,
doubleinside a struct is aligned to 4 bytes, not 8. Windows and Linux agree for most x86-64 types, butlongandlong doublediffer. Never hard-code offsets across platforms. - Language differences. C and C++ keep declaration order. Rust's default representation may reorder fields to reduce padding, but
#[repr(C)]keeps declaration order and C rules. - Nested structs. An inner struct keeps its own alignment and tail padding. Putting a
charafter a nested struct can waste space even after you sort the outer fields. Consider flattening hot data. - Heap allocation.
mallocreturns memory aligned for any standard type, usually 16 bytes, but not 64. If you need line-aligned data, usealigned_alloc,posix_memalign, oralignas(64)on the type. - Over-alignment is a cost. Aligning every small object to 64 bytes wastes space. Do it only where you have a measured reason, such as the false sharing case covered later.
Summary table
| Technique | Cost | Typical benefit |
|---|---|---|
| Sort fields by descending alignment | None at run time | Removes interior padding |
| Narrower field types | Range limits | Smaller struct, more elements per line |
| Bit fields or flag sets | Extra instructions | Compresses booleans |
| Packed attribute | Misaligned access | Smallest size, risky for hot data |
| `alignas(64)` | Wasted space | Prevents line sharing and straddling |
Exercise
A struct has fields in this order: char a; int b; char c; double d;. On x86-64 with typical alignment (char 1, int 4, double 8), what is its size, and what is the smallest size you can reach by reordering?
Show answer
In the original order, a is at 0, 3 bytes of padding, b at 4, c at 8, 7 bytes of padding, d at 16, giving 24 bytes. Reordered as double d; int b; char a; char c;, the offsets are 0, 8, 12, 13, and 2 bytes of tail padding round the size to 16 bytes.
Exercise
You have an array of one million 24-byte structs and you reorder the fields so the struct becomes 16 bytes. Give two reasons the loop that scans the array may speed up by more than the 1.5x ratio of sizes would suggest.
Show answer
First, the 16 MB array may fit in a cache level that the 24 MB array did not, so misses drop sharply instead of proportionally. Second, 16-byte elements never straddle a 64-byte line, so no element needs two line fetches, while some 24-byte elements do.