
Optimizing Rust with std::mem::align_of and Cache-Aligned Data Layouts
Why alignment matters
Modern CPUs move data in cache lines, not individual bytes. If a frequently accessed field straddles cache lines, or if unrelated threads repeatedly modify values that share a line, performance can degrade sharply. Alignment is the rule that determines where a value may begin in memory, and Rust exposes that information through std::mem::align_of.
At a high level, alignment affects:
- Load/store efficiency: aligned accesses are usually cheaper.
- Cache locality: related data packed together can be fetched together.
- False sharing: independent data on the same cache line can create contention.
- ABI and FFI correctness: some external APIs require specific alignment.
Rust already aligns many types sensibly, but default layout is not always optimal for performance-sensitive code.
Inspecting type alignment in Rust
The standard library provides two useful functions:
std::mem::size_of::<T>()std::mem::align_of::<T>()
These let you reason about how a type will be stored.
use std::mem::{align_of, size_of};
fn main() {
println!("u8: size={}, align={}", size_of::<u8>(), align_of::<u8>());
println!("u64: size={}, align={}", size_of::<u64>(), align_of::<u64>());
#[repr(C)]
struct PacketHeader {
version: u8,
flags: u8,
length: u32,
}
println!(
"PacketHeader: size={}, align={}",
size_of::<PacketHeader>(),
align_of::<PacketHeader>()
);
}
A common surprise is that size_of::<T>() is often larger than the sum of its fields. That extra space is padding inserted to satisfy alignment constraints.
Practical rule
If a type is used in a tight loop, a queue, or a large array, inspect both size and alignment. A few bytes of padding multiplied by millions of elements can become meaningful memory pressure.
Reordering fields to reduce padding
Rust does not guarantee field order optimization for repr(Rust) types, but in practice the compiler may still insert padding based on the declared order. If you need a stable layout for FFI, use #[repr(C)]. If you want better packing for internal data, field order matters.
Consider this example:
#[repr(C)]
struct BadLayout {
a: u8,
b: u64,
c: u8,
}
#[repr(C)]
struct BetterLayout {
b: u64,
a: u8,
c: u8,
}
The first layout likely wastes more space because the u64 must be aligned to 8 bytes. By placing the largest-aligned field first, you often reduce padding.
Best practice
Order fields from largest alignment to smallest when:
- the type is internal to your crate,
- you care about memory footprint,
- and you do not rely on a specific external ABI.
If the type is used with FFI, do not reorder fields unless the foreign definition is updated too.
Using align_of to design cache-friendly containers
Alignment is not only about single structs. It also matters when you store many values in arrays or vectors. A type with a large alignment can increase the stride between elements, which may reduce cache density.
| Design choice | Effect | When to use |
|---|---|---|
| Smaller alignment | More elements per cache line | Dense read-heavy collections |
| Larger alignment | Better isolation, fewer boundary issues | Hot mutable fields, FFI, SIMD-friendly data |
| Field reordering | Less padding inside each element | Internal structs with many fields |
repr(C) | Predictable layout | FFI and binary compatibility |
A Vec<T> stores elements contiguously, so each element’s size and alignment directly affect how many fit in cache. If T is 64 bytes, a 64-byte cache line may hold exactly one element. If T is 72 bytes, each element spans more than one line, increasing memory traffic.
Avoiding false sharing with cache-line padding
False sharing happens when two threads update different variables that happen to live on the same cache line. Even though the values are logically independent, the cache coherence protocol treats the line as a shared unit, causing unnecessary invalidation traffic.
A common fix is to pad or align frequently written per-thread counters so each one occupies its own line.
use std::sync::atomic::{AtomicU64, Ordering};
#[repr(align(64))]
struct PaddedCounter {
value: AtomicU64,
}
impl PaddedCounter {
fn new() -> Self {
Self {
value: AtomicU64::new(0),
}
}
fn inc(&self) {
self.value.fetch_add(1, Ordering::Relaxed);
}
fn get(&self) -> u64 {
self.value.load(Ordering::Relaxed)
}
}
Here #[repr(align(64))] requests 64-byte alignment, which is a common cache-line size on many systems. This does not guarantee a cache line boundary on every architecture, but it is a practical and widely used strategy.
When this helps
Use cache-line padding when:
- multiple threads update adjacent counters,
- you maintain per-core or per-worker statistics,
- a lock-free structure has hot metadata fields,
- or a benchmark shows coherence traffic dominating runtime.
When it does not help
Padding is not free. It increases memory usage and can reduce cache density. Do not pad every type by default. Reserve it for fields that are heavily written and independently accessed.
Choosing between packing and isolation
There is a trade-off between compactness and isolation. Compact layouts improve cache utilization for sequential reads, while isolated layouts reduce interference for concurrent writes.
A useful mental model:
- Read-mostly data: pack tightly.
- Write-heavy shared data: isolate aggressively.
- Mixed workloads: separate hot mutable fields from cold metadata.
For example, consider a task scheduler that stores task status and statistics together:
struct TaskState {
status: u8,
retries: u32,
last_run_ns: u64,
debug_name: String,
}
If status is updated frequently and debug_name is read rarely, the combined layout may be suboptimal. A better design is to split hot and cold data:
#[repr(align(64))]
struct HotTaskState {
status: u8,
retries: u32,
last_run_ns: u64,
}
struct TaskMeta {
debug_name: String,
}
struct Task {
hot: HotTaskState,
meta: TaskMeta,
}
This separation keeps the frequently touched fields compact and allows the cold metadata to move out of the hot path.
Alignment and FFI boundaries
When interoperating with C or other languages, alignment becomes part of the contract. A foreign function may expect a struct to match a C layout exactly, including padding and alignment.
Use #[repr(C)] for types shared across FFI boundaries. Then verify assumptions with size_of and align_of.
use std::mem::{align_of, size_of};
#[repr(C)]
struct CHeader {
tag: u32,
len: u16,
flags: u16,
}
fn main() {
assert_eq!(size_of::<CHeader>(), 8);
assert_eq!(align_of::<CHeader>(), 4);
}
If the foreign side expects a specific packing rule, match it exactly. Do not assume Rust’s default layout is compatible.
Important caution
Avoid using #[repr(packed)] unless you truly need it for binary compatibility. Packed structs can create unaligned field accesses, which are awkward or unsafe to use efficiently. In performance-sensitive code, it is usually better to preserve alignment and copy data into a better-shaped internal representation.
Measuring the impact correctly
Alignment changes can help, but only if they address a real bottleneck. Measure before and after with representative workloads.
Focus on:
- throughput under realistic contention,
- memory footprint for large collections,
- cache miss rates if your profiling tools expose them,
- and latency distribution, not just averages.
A layout that improves a microbenchmark may hurt production if it increases memory usage too much or changes access patterns elsewhere.
Good workflow
- Identify a hot data structure.
- Inspect its size and alignment.
- Check whether fields are read or written together.
- Reorder or split fields if needed.
- Add padding only for proven contention.
- Re-measure with production-like input.
Common patterns that benefit from alignment-aware design
Per-thread counters
Counters updated by different threads should not sit next to each other in memory. Use padded wrappers or arrays of aligned structs.
Ring buffers and queues
Metadata such as head and tail indices can become hot under contention. Separating them or aligning them to different cache lines can reduce coherence traffic.
Large tables of records
If you store millions of records, every byte of padding matters. Reordering fields can save memory and improve cache residency.
FFI buffers
External APIs may require specific alignment for vectorized loads or platform-specific instructions. In those cases, alignment is not just a performance hint; it is a correctness requirement.
A practical checklist
Use this checklist when optimizing memory layout:
- Inspect
size_of::<T>()andalign_of::<T>(). - Reorder fields to reduce padding in internal structs.
- Use
#[repr(C)]only when layout stability is required. - Use
#[repr(align(N))]for hot mutable state that suffers from false sharing. - Split hot and cold fields when access patterns differ.
- Avoid
repr(packed)unless compatibility demands it. - Measure the real workload before keeping the change.
Conclusion
Alignment is a low-level detail with high-level consequences. In Rust, std::mem::align_of gives you the visibility needed to reason about memory layout, while #[repr(align(N))] and careful struct design let you shape that layout for better cache behavior.
The biggest wins usually come from two simple ideas: pack read-heavy data tightly, and isolate write-heavy data that would otherwise contend on the same cache line. Used thoughtfully, these techniques can improve throughput without changing your algorithms at all.