Cache Behavior: AoS vs SoA
A modern CPU can do several arithmetic operations per nanosecond, but fetching data from main memory takes on the order of a hundred nanoseconds. Caches hide that gap: small, fast memories (L1, L2, L3) that keep recently used data close to the core. Whether your loop runs at full speed or spends most of its time waiting depends mostly on how your data is laid out.
Three facts drive everything in this lesson:
- Memory moves between RAM and the caches in cache lines of 64 bytes (on current x86 and most ARM cores; some Apple cores use 128). Touch one byte and you pay for the whole line.
- Caches are small. Typical sizes: L1 data 32–64 KB per core, L2 0.5–2 MB, L3 several to tens of MB shared.
- Hardware prefetchers detect sequential access and fetch lines before you ask. Linear walks through arrays are nearly free; random jumps through memory (pointer chasing) are not.
Note: Timing results on a shared Compiler Explorer machine are noisy, so the programs here don't measure time. They count what the hardware would have to do: cache lines loaded and misses in a simulated cache. Real measurements belong in your own profiler on your own target hardware (see Profiling).
Padding: the cheapest optimization
The compiler inserts padding so each member is aligned. Member order changes the size of a struct, and therefore how many fit in a cache line:
#include <cstdio>
#include <cstdint>
struct Careless { // members in "logical" order
bool active;
double x;
std::uint8_t team;
double y;
std::uint16_t flags;
float health;
};
struct Ordered { // largest alignment first
double x, y;
float health;
std::uint16_t flags;
std::uint8_t team;
bool active;
};
int main() {
std::printf("Careless: %zu bytes, %zu per 64-byte line\n", sizeof(Careless), 64 / sizeof(Careless));
std::printf("Ordered : %zu bytes, %zu per 64-byte line\n", sizeof(Ordered), 64 / sizeof(Ordered));
}Careless: 40 bytes, 1 per 64-byte line
Ordered : 24 bytes, 2 per 64-byte line
Same data, a third less memory traffic. Sorting members from largest to smallest alignment is a habit worth having for any struct stored by the thousand.
AoS, SoA and hot/cold splitting
An array of structures (AoS) stores each entity's fields together. A structure of arrays (SoA) stores each field in its own array. A movement system that reads position and velocity but not name, health, AI state and the rest of the entity uses only a fraction of every AoS cache line it loads; with SoA every loaded byte is useful.
AoS: [pos vel hp name ai ...][pos vel hp name ai ...][pos vel hp name ai ...]
SoA: pos: [p p p p p p p p ...] vel: [v v v v v v v v ...] hp: [...] name: [...]
Hot/cold AoS: hot: [pos vel][pos vel][pos vel] ... cold: [hp name ai ...] ...The program counts how many distinct 64-byte lines each layout touches when a system reads pos and vel of 10 000 entities:
#include <cstddef>
#include <cstdio>
#include <set>
struct Vec3 { float x, y, z; };
struct EntityAoS { // 96 bytes: hot data mixed with cold data
Vec3 pos, vel; // 24 bytes the movement system needs
float health, armor;
char name[32];
int aiState, team, flags, meshId;
float cooldowns[4];
};
struct HotAoS { Vec3 pos, vel; }; // hot/cold split: only what the update reads
constexpr std::size_t kLine = 64;
constexpr int N = 10000;
// Count distinct cache lines touched by reading `bytes` at each address.
template <class F> std::size_t linesTouched(F addressOf, std::size_t bytes) {
std::set<std::size_t> lines;
for (int i = 0; i < N; i++) {
std::size_t a = addressOf(i);
for (std::size_t b = a / kLine; b <= (a + bytes - 1) / kLine; b++) lines.insert(b);
}
return lines.size();
}
int main() {
std::printf("sizeof(EntityAoS) = %zu, sizeof(HotAoS) = %zu\n", sizeof(EntityAoS), sizeof(HotAoS));
const std::size_t posOff = offsetof(EntityAoS, pos); // vel follows pos directly
// Pretend every array starts at a line-aligned address.
std::size_t aos = linesTouched([&](int i) { return i * sizeof(EntityAoS) + posOff; }, 2 * sizeof(Vec3));
std::size_t hot = linesTouched([&](int i) { return i * sizeof(HotAoS); }, sizeof(HotAoS));
const std::size_t velBase = 1 << 20; // second array far away from the first
std::size_t soa = linesTouched([&](int i) { return i * sizeof(Vec3); }, sizeof(Vec3))
+ linesTouched([&](int i) { return velBase + i * sizeof(Vec3); }, sizeof(Vec3));
const double usefulBytes = double(N) * 2 * sizeof(Vec3);
auto row = [&](const char* name, std::size_t lines) {
std::printf("%-12s %6zu lines = %7zu KB loaded, %5.1f%% of loaded bytes used\n", name, lines,
lines * kLine / 1024, 100.0 * usefulBytes / double(lines * kLine));
};
row("AoS", aos);
row("hot/cold", hot);
row("SoA", soa);
}sizeof(EntityAoS) = 96, sizeof(HotAoS) = 24
AoS 10000 lines = 625 KB loaded, 37.5% of loaded bytes used
hot/cold 3750 lines = 234 KB loaded, 100.0% of loaded bytes used
SoA 3750 lines = 234 KB loaded, 100.0% of loaded bytes used
The AoS layout drags about 2.7 times as much memory through the cache for the same work: each entity costs a whole 64-byte line, of which only 24 bytes are used. On real hardware, a loop like this is limited by memory bandwidth long before arithmetic, so the run time follows the "KB loaded" column closely once the data no longer fits in cache.
SoA is not always the winner. If a system reads all fields of each element (a physics solver reading position, velocity, mass and inertia together), AoS of exactly those fields is just as good and simpler. Many engines use a mix: entities grouped by which components they have, each component stored as a packed array. That is what an archetype ECS does.
Pointer chasing
Prefetchers can't predict where the next node of a linked list or tree lives. Each step is a dependent load, and if the node is not in cache, the CPU waits for main memory. This program runs both traversals through a small simulated LRU cache (4 KB, 64 lines) and counts misses. The list nodes are scattered, as they would be after a level of allocating and freeing:
#include <cstdint>
#include <cstdio>
#include <list>
#include <unordered_map>
#include <vector>
// Fully associative LRU cache of `capacity` lines; access() returns true on a miss.
struct CacheSim {
std::size_t capacity;
std::list<std::size_t> lru; // front = most recent
std::unordered_map<std::size_t, std::list<std::size_t>::iterator> where;
int misses = 0, accesses = 0;
explicit CacheSim(std::size_t lines) : capacity(lines) {}
void access(std::size_t address) {
std::size_t line = address / 64;
accesses++;
auto it = where.find(line);
if (it != where.end()) { lru.splice(lru.begin(), lru, it->second); return; }
misses++;
lru.push_front(line);
where[line] = lru.begin();
if (lru.size() > capacity) { where.erase(lru.back()); lru.pop_back(); }
}
};
int main() {
const int N = 4096;
const std::size_t nodeSize = 16; // value + next pointer
// Array: element i at address i * 16
CacheSim arrayCache{64};
for (int i = 0; i < N; i++) arrayCache.access(std::size_t(i) * nodeSize);
// Linked list: same nodes, but visited in a scrambled memory order
std::vector<std::size_t> slot(N);
for (int i = 0; i < N; i++) slot[i] = i;
std::uint32_t state = 12345; // xorshift, fixed seed
for (int i = N - 1; i > 0; i--) { // Fisher-Yates shuffle
state ^= state << 13; state ^= state >> 17; state ^= state << 5;
std::swap(slot[i], slot[state % (i + 1)]);
}
CacheSim listCache{64};
for (int i = 0; i < N; i++) listCache.access(slot[i] * nodeSize);
std::printf("array: %d accesses, %4d misses (%.1f%%)\n", arrayCache.accesses, arrayCache.misses,
100.0 * arrayCache.misses / arrayCache.accesses);
std::printf("list : %d accesses, %4d misses (%.1f%%)\n", listCache.accesses, listCache.misses,
100.0 * listCache.misses / listCache.accesses);
}array: 4096 accesses, 1024 misses (25.0%)
list : 4096 accesses, 3891 misses (95.0%)
The array misses once per line (every fourth element) and the prefetcher would hide most of even those. The scattered list misses on almost every node, and each miss is a full trip to memory that the prefetcher cannot start early because the address is only known after the previous load completes.
Practical rules
- Iterate arrays, not pointers.
std::vector<T>overstd::vector<T*>, overstd::list<T>. Packed arrays of components beat object graphs ofnew-allocated entities. - Split hot from cold. Keep what the per-frame loop reads in a small struct; move names, debug data and rarely used fields elsewhere, linked by index.
- Shrink data.
floatinstead ofdouble,uint16_tindices, bitfields for flags, quantized normals. Smaller data means more per line. - Process in batches. Do one operation over all elements, then the next operation, instead of running every operation per element. Each pass then streams through memory once.
- Measure on the target. Tools such as Intel VTune, AMD uProf, Linux
perf stat -e cache-missesand Apple Instruments report real cache misses. See Toolkit: Debuggers, Sanitizers and Profilers.
Test yourself
In the line-counting example, why does the AoS layout load far more memory than SoA for the same movement update?
- AoS structs are not aligned
- Whole 64-byte lines are loaded, but the update uses only the 24 bytes of position and velocity in each
- SoA compresses the data
- The AoS loop runs more iterations
Why is traversing a scattered linked list slow even when each node is small?
- Lists use more instructions per element
- Each next address is known only after the previous load, so the prefetcher can't hide the cache misses
- Linked lists are not allowed in caches
- The compiler can't optimize loops over lists
When is AoS just as good as SoA?
- Never
- When the loop uses all (or nearly all) fields of each element
- When the array is sorted
- When elements are larger than a cache line