Memory Hierarchy
For a loop that sums only the x coordinates as above, why does converting to a structure of arrays (a separate array per field) tend to be faster?
struct P { float x, y, z, mass; };
struct P p[N];
for (i = 0; i < N; i++)
sx += p[i].x;
- AAs an array of structures, the compiler cannot generate instructions that read only the x field
- BSeparate arrays make the floating-point computation more precise
- CThe x values are contiguous, so fetched lines carry no unneeded fields
Show answer and explanation
Answer: C. The x values are contiguous, so fetched lines carry no unneeded fields
In an array of structures (AoS), x, y, z and mass form a 16-byte group, so even a loop reading only x wastes three quarters of each 64-byte line. With a structure of arrays (SoA), the x values are contiguous, every fetched line is fully used, and memory traffic drops to about a quarter. It also makes SIMD vectorization easier. Compilers can read x from AoS, and changing the layout does not change numerical precision.
- A. Compilers can read x from an AoS layout just fine.
- B. Changing the data layout does not change precision.
- C. Correct. Only the needed x values are contiguous, so lines are used without waste.