Cache locality and data layout
Quick answer
Cache locality describes how memory access patterns reuse nearby data. Layout can influence cache traffic, but the effect depends on hardware and the workload.
Layout and traversal
An array of structs groups fields per item; a struct of arrays groups the same field across items. If an algorithm reads one field from many items, the latter may reduce unnecessary memory traffic. Rust default struct layout is not a stable field-order ABI; repr(C) provides specified C-style ordering and padding rules, with target-dependent sizes. Cache lines, alignment and false sharing need measurement, not guessed constants.
struct Item { price: u32, stock: u32 }fn main() { let items = [Item { price: 4, stock: 2 }, Item { price: 7, stock: 3 }]; let prices = [4, 7]; let stocks = [2, 3]; let a: u32 = items.iter().map(|x| x.price * x.stock).sum(); let b: u32 = prices.iter().zip(stocks).map(|(p, s)| p * s).sum(); println!("{a} {b}");}Expected stdout (not executed):
29 29Both models compute the same total; this is not a timing test.
use std::mem::{align_of, size_of};#[repr(C)]struct Record { flag: u8, value: u32, tail: u8 }fn main() { println!("size={} alignment={}", size_of::<Record>(), align_of::<Record>()); }Manual local Rust/Cargo candidate; not executed. Expected behavior:
Reports target-dependent size and alignment; record actual values locally.Padding can make size larger than the sum of field sizes.
Common mistake
Do not assert that a struct-of-arrays layout is always faster.
Try it yourself
Benchmark scanning only prices versus scanning all fields on both layouts using equal input.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cache locality and data layout — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A workload reads only prices from millions of records. Which layout is a candidate for better locality?
Cache locality and data layout — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust struct Item { price: u32, stock: u32 } fn main() { let items = [Item { price: 4, stock: 2 }, Item { price: 7, stock: 3 }]; let prices = [4, 7]; let stocks = [2, 3]; let a: u32 = items.iter().map(|x| x.price * x.stock).sum(); let b: u32 = prices.iter().zip(stocks).map(|(p, s)| p * s).sum(); println!("{a} {b}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Cache locality and data layout — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::mem::{align_of, size_of}; #[repr(C)] struct Record { flag: u8, value: u32, tail: u8 } fn main() { println!("size={} alignment={}", size_of::<Record>(), align_of::<Record>()); } ``` Which outcome or interpretation best matches this example?