cache-lens
A static analyzer that detects cache-unfriendly Array-of-Structures (AoS) usage in Rust and suggests a Structure-of-Arrays (SoA) refactor.
It parses your source with syn, finds loops that iterate over a Vec/
array/slice of some struct, and flags the ones where only a small slice of
that struct's fields are ever touched inside the loop — the classic pattern
where every iteration drags unused fields into the cache for free.
$ cache-lens examples/monster_sim.rs
cache-lens found 7 potential AoS→SoA opportunities across 1 file(s):
────────────────────────────────────────────────────────────────────────────
[HIGH] examples/monster_sim.rs:16
struct `Monster` (7 fields, defined at line 4) in loop `for`
Loop variable `monster` over `monsters` — 1/7 fields touched (~5% of the
struct's bytes are actually used per iteration)
Hot fields (touched in the loop):
✓ hp f32 1 read(s), 2 write(s), ~4B
Cold fields (never touched — dead weight on every cache line):
✗ mana f32 ~4B
✗ name String ~24B
✗ inventory Vec<String> ~24B
✗ level u8 ~1B
✗ experience u32 ~4B
✗ position (f32, f32, f32) ~12B
Suggested refactor — Structure of Arrays:
pub struct Monsters {
pub hps: Vec<f32>,
pub manas: Vec<f32>,
pub names: Vec<String>,
pub inventories: Vec<Vec<String>>,
pub levels: Vec<u8>,
pub experiences: Vec<u32>,
pub positions: Vec<(f32, f32, f32)>,
}
Alternative — let the `soa-derive` crate generate the container:
#[derive(StructOfArray)]
pub struct Monster { ... }
Build & run
cargo build --release
./target/release/cache-lens <files or directories...>
CLI
cache-lens [OPTIONS] <PATHS>...
<PATHS>... files or directories (recursed, skipping
target/ .git/ node_modules/)
--min-fields <N> min fields for a struct to be a candidate [default: 3]
--max-access-ratio <R> flag when <= R fraction of fields are touched [default: 0.5]
--json machine-readable output for CI/tooling
--strict exit 1 if anything was found (CI gating)
-q, --quiet no "scanning N files" banner
How detection works
Three syn::visit::Visit passes, each with a single job:
StructCollector— walks every input file once and records every named-field struct definition (name, fields, types) into one global table, before any loop analysis happens. This is what lets a struct defined inmodel.rsbe recognized in a loop over insimulation.rs.CacheLensVisitor— walks each file again, tracking which local variables / fn parameters /self.fields are collections of a known struct, and recognizing loop shapes:for,whilewith manual indexing, and.iter()/.iter_mut()/.into_iter()chained intofor_each,map,filter,any,all,find, orinspect.FieldAccessCollector/IndexedFieldAccessCollector— for each recognized loop, one of these two small visitors walks just that loop's body and records exactly which fields are read or written, including a best-effort token scan through macro calls (println!,assert!, ...) so fields only used for logging still count as "touched."
A finding fires when a struct has at least --min-fields fields, at least
one field is touched, and the touched fraction is at or below
--max-access-ratio — i.e. "a few fields are clearly hot, and at least one
field is provably cold across the whole loop body."
Severity is HIGH when either the field-count ratio or the (heuristic)
byte-size ratio is ≤ 30%, MEDIUM otherwise.
Known limitations
This is a syntax-level heuristic tool, not a type checker — it deliberately
trades some precision for not needing a full rustc frontend:
- No cross-module path resolution. Structs are matched by bare identifier. Two unrelated structs that happen to share a name in different modules are treated as the same struct. Rare, but possible.
- Only explicitly-typed bindings are tracked.
let m: Vec<Monster> = ..and typed fn parameters are recognized;let m = Vec::new()with no annotation is not inferred, since that needs real type inference. - Adapter chains aren't unwrapped.
monsters.iter().filter(..).for_each(..)won't be recognized — only a direct.iter()/.iter_mut()/.into_iter()receiver on the terminal closure method is. - Byte-size estimates are directional, not exact. They ignore alignment,
padding, and niche-filling optimizations. Treat "~30% of the struct is
useful here" as a heuristic signal, not a
std::mem::size_ofguarantee. - One flat scope per function, not per nested block — a good-enough approximation for a lint tool, not real shadowing semantics.
- It can't see call frequency. A loop over 8 elements that runs once at
startup matches the same syntactic pattern as a hot loop over 8 million
elements that runs every frame. Running
cache-lenson its own source turns up exactly this: it (correctly, syntactically) flags a.filter()over a short-livedVec<Finding>in the reporting code. Treat findings as "worth a look," especially outside code you know is hot. - Suggested field pluralization is a simple heuristic (
hp→hps,inventory→inventories), not a grammar engine — rename generated fields to taste.