Sub topic 8
Array of Structs versus Struct of Arrays
This chapter assumes you know C structs and pointers, and that you have read the earlier chapters on cache lines, traversal order, and padding. You should be comfortable with the idea that a cache line (commonly 64 bytes) is the unit the CPU loads from memory.
The two layouts
Suppose you store many particles, each with a position, a velocity, and an id. There are two common ways to lay them out.
- Array of structs (AoS): one array whose elements are complete records. All fields of particle 0 sit together, then all fields of particle 1, and so on.
- Struct of arrays (SoA): one array per field. All
xvalues sit together, then allyvalues, and so on. Particleiis spread across several arrays at indexi.
AoS is how most people write code first, because it matches the mental model of "a list of objects". SoA matches how the hardware reads memory when a loop touches only some fields.
#include <stddef.h>
/* Array of structs: summing x also pulls y, z, and the rest into cache. */
struct ParticleAos {
float x, y, z;
float vx, vy, vz;
int id;
};
float sum_x_aos(const struct ParticleAos *p, size_t n) {
float s = 0.0f;
for (size_t i = 0; i < n; i++)
s += p[i].x;
return s;
}
/* Struct of arrays: each field is stored contiguously. */
struct ParticlesSoa {
float *x, *y, *z;
float *vx, *vy, *vz;
int *id;
size_t n;
};
float sum_x_soa(const struct ParticlesSoa *p) {
float s = 0.0f;
for (size_t i = 0; i < p->n; i++)
s += p->x[i];
return s;
}Why the layout changes cache traffic
struct ParticleAos holds seven 4-byte fields, so it is 28 bytes. Two consecutive elements do not fit evenly into a 64-byte line, so records straddle line boundaries. The loop in sum_x_aos reads 4 useful bytes out of every 28. Over a large array, the CPU loads roughly 7 times more memory than the loop needs.
In sum_x_soa, the x array is dense. A 64-byte line holds 16 consecutive x values, and the loop uses all 16. The loop moves about one seventh of the data, so it runs faster once the array is larger than the cache. SIMD (vector) instructions also benefit, because the compiler can load several adjacent x values into one register without gathering them from strided positions.
The diagram below shows the same data in both layouts and which bytes a loop over x pulls into a cache line.
When SoA wins and when AoS wins
The right choice depends on which fields each loop touches together. Use the access pattern, not habit, to decide.
| Workload | Better layout | Reason |
|---|---|---|
| Loop reads one or two fields across all elements | SoA | Every loaded byte is used |
| Loop reads all fields of one element, then moves on | AoS | One element's fields share a line or two |
| Random access to whole records by index or id | AoS | One miss brings in the whole record, SoA needs one miss per field array |
| Vectorized math over many elements | SoA | Adjacent values load directly into vector registers |
| Fields that are always read together, such as `x`, `y`, `z` | Hybrid | Keep them together as a small struct |
The random-access row is the one people forget. If you look up particle 5000 and read all seven fields, AoS touches one or two cache lines. SoA touches seven, in seven different arrays, each a separate miss. SoA is not simply "better". It trades whole-record locality for per-field locality.
Hybrid layouts
Real data often has groups of fields that are used together. Position components x, y, z are almost always read as a set, so splitting them into three arrays gains little and costs extra cache lines. A common compromise is an array of small structs per group, sometimes called AoSoA when blocks of a fixed size are interleaved.
#include <stddef.h>
struct Vec3 { float x, y, z; };
struct ParticlesHybrid {
struct Vec3 *pos; /* positions stored together */
struct Vec3 *vel; /* velocities stored together */
int *id; /* rarely used in hot loops */
size_t n;
};
void integrate(struct ParticlesHybrid *p, float dt) {
for (size_t i = 0; i < p->n; i++) {
p->pos[i].x += p->vel[i].x * dt;
p->pos[i].y += p->vel[i].y * dt;
p->pos[i].z += p->vel[i].z * dt;
}
}The integrate loop reads and writes positions and velocities but never touches id, so id stays out of the cache. This connects to the next chapter, where rarely used fields are separated from hot ones.
Costs and gotchas
SoA has costs that do not show up in a micro-benchmark of one loop.
- More pointers and allocations. The SoA struct above holds seven pointers. Each array needs its own allocation, or you must carve them from one block and track the offsets.
- Insertion and deletion touch every array. Removing particle
iby swapping in the last element means one write per field array, not one record copy. - Sorting and reordering. Sorting by one key must permute every array in step. An index array sorted by the key, followed by a gather pass per field, is the usual approach.
- Readability.
p->x[i]is harder to pass around than astruct Particle *. Wrappers or accessor functions help, but add code. - Many streams. A loop that reads eight different SoA arrays keeps eight streams active. The hardware prefetcher tracks a limited number of streams, and cache associativity can cause conflicts when arrays have power-of-two spacing. If a loop touches most fields, AoS can be as fast or faster.
Alignment in SoA
Each field array can be aligned independently. Aligning every array to a 32 or 64 byte boundary lets vector loads stay inside one cache line. In C11 you can request this with aligned_alloc, whose size argument must be a multiple of the alignment.
#include <stdlib.h>
#include <stddef.h>
float *alloc_floats(size_t n) {
size_t bytes = n * sizeof(float);
size_t rounded = (bytes + 63) / 64 * 64;
return aligned_alloc(64, rounded);
}Release the memory with free, as with malloc. Remember that 64 is a common line size, not a guaranteed one.
Checking the result
To confirm that SoA helps, time both versions on an array larger than the last-level cache, then compare cache-miss counts with a tool such as perf stat -e cache-misses. Use the same data and the same number of repetitions. If the SoA loop is no faster, the loop is probably limited by something other than memory, or the data already fits in cache.
Exercise
A struct has fields double price; double qty; char name[48]; and you keep 10 million of them in an array. One loop computes the sum of price * qty over all elements. Another loop looks up a single element by index and prints all fields. Which layout suits each loop, and why?
Show answer
The sum loop suits SoA (or a split into a hot struct of price and qty plus a separate name array), because it needs 16 bytes per element but AoS would load the full 64-byte record, so about three quarters of each cache line is wasted. The single-element lookup suits AoS, because all fields live in one or two adjacent cache lines, while SoA would take a separate miss in each field array. If both loops matter, keep price and qty together and move name into a separate array.
Exercise
Why can a loop that reads all seven fields of every particle run slower with SoA than with AoS?
Show answer
SoA makes the loop read seven separate memory streams at once. That can exceed the number of streams the prefetcher tracks, and arrays whose addresses differ by a power of two can compete for the same cache sets. AoS reads one stream where every loaded byte is used, so it has no wasted bandwidth to recover.