Struct Layout: Combined vs Split Field Storage
Question 15 / 51 • Correct so far: 0 (0 answered)
Mixed Struct
struct Entity {
float x, y, z;
float health;
char name[48];
};
float sumX = 0.0f, sumHealth = 0.0f;
for (const auto& e : ENTITIES) {
sumX += e.x;
sumHealth += e.health;
} Split Struct
struct EntityHot {
float x, y, z;
float health;
};
struct EntityCold {
char name[48];
};
float sumX = 0.0f, sumHealth = 0.0f;
for (const auto& e : HOT) {
sumX += e.x;
sumHealth += e.health;
} Shared test data (shared-setup)
constexpr std::size_t kNumEntities = 524288; Which snippet is faster?
Snippet B is faster. In snippet A, frequently used fields are mixed with infrequently used data, so cache lines carry extra bytes the loop does not need. Splitting hot fields into a compact layout improves cache efficiency.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Mixed Struct | 447 us | 1.0× |
| Split Struct | 303 us | 1.5× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.