C Mastery / Cache and Memory Locality, Data Layout (AoS/SoA)
Part 9 — Performance

Cache and Memory Locality, Data Layout (AoS/SoA)

This chapter explains cache and memory locality and the critical data-layout choice between Array-of-Structs (AoS) and Struct-of-Arrays (SoA).

Why This Matters

Memory access, not instruction count, often dominates performance. How you lay out data determines cache hit rates and therefore speed. AoS vs. SoA is a single decision that can change performance by an order of magnitude.

Prerequisites

Core Concept

Locality

soon.

accessed soon.

Caches exploit both. Contiguous, stride-1 access is ideal; large strides waste cache lines.

AoS vs. SoA

For a collection of objects with multiple fields:

Each element's fields are contiguous.

Each field is a separate contiguous array.

Examples

AoS

struct Point { float x, y, z; };
struct Point points[N];

for (int i = 0; i < N; i++)
    points[i].x += 1.0f;   /* touches every field (x, y, z) for each i */

SoA

struct Points { float x[N], y[N], z[N]; } pts;

for (int i = 0; i < N; i++)
    pts.x[i] += 1.0f;      /* touches only x[]; y/z stay in cache */

If a loop uses only x, SoA keeps the working set dense and cache-friendly; AoS pulls in unused y/z, wasting bandwidth.

How It Works

When you access pts.x[i], the CPU fetches a cache line of consecutive x values. AoS interleaves y/z between the xs, so the same loop fetches three times as much data for one useful field. SoA gives dense access to the field you actually use.

Variations

Hybrid / blocked layouts

For some algorithms, block/tile data or use a hybrid to balance locality of different access patterns.

Hot/cold splitting

Move rarely used fields into a separate structure so hot fields stay dense.

Common Mistakes

Undefined Behavior

access would be UB, but that is separate.)

Portability

the principle is universal.

Under the Hood

A cache line is ~64 bytes. SoA puts consecutive xs in the same lines; AoS interleaves fields. SIMD also benefits from SoA (contiguous lanes).

Practical Usage

Exercises

1. Benchmark a loop that touches one field in AoS vs. SoA and compare. 2. Explain why the AoS version fetches more cache lines. 3. Convert a struct-of-structs to SoA for a particle system.

Deep Challenge

Write a small particle-update loop in both AoS and SoA, benchmark with perf stat (cache misses), and explain the difference in terms of cache lines and memory bandwidth.

References

optimization guides.

Verification

verified.`

Progress

Concept checkboxes

Mastery levels

ConceptCurrent level (0–8)Target level
c.perf.cache-locality06
c.perf.mem-locality06
c.perf.aos-soa06