In Rust, the number of bytes a value of a sized (Sized) type takes is fixed at compile time, and std::mem::size_of shows it directly. When a heap allocation happens is visible in code too, through values like Vec::capacity. In an API server that builds many small structs and Vecs per request, value size and allocation count can affect memory use and latency. I wanted to measure for myself how many bytes a type takes and how many times a piece of code allocates.

Sizes and layout come from size_of, align_of, and offset_of! output, and allocation cost from criterion benchmarks. Every example below was compiled with rustc 1.94.1, edition 2021, and run on aarch64-apple-darwin (Apple M4 Pro, macOS 15.1). Sizes are for a 64-bit target, and any layout the Reference does not guarantee is what this version produced. The benchmark crates are smallvec 1.16.5, bumpalo 3.20.4, and criterion 0.5.1.

Size and alignment — field order decides the padding

repr(C) keeps declaration order and needs 5 padding bytes for 12 bytes; the default layout reorders fields into 8 bytes#[repr(C)] — 12B0kindpad4id8flagspaddefault layout — 8B0id4flagskindpadone row = 4-byte alignment unit[EventC; 4] = 48B, [Event; 4] = 32B

Every type has a size and an alignment. A value with alignment 4 can only sit at an address that is a multiple of 4. I declared the same three fields with the default layout and with #[repr(C)], and printed the offsets.

use std::mem::{align_of, offset_of, size_of};

struct Event {
    kind: u8,
    id: u32,
    flags: u16,
}

#[repr(C)]
struct EventC {
    kind: u8,
    id: u32,
    flags: u16,
}

fn main() {
    println!("u8  size {} align {}", size_of::<u8>(), align_of::<u8>());
    println!("u16 size {} align {}", size_of::<u16>(), align_of::<u16>());
    println!("u32 size {} align {}", size_of::<u32>(), align_of::<u32>());
    println!("u64 size {} align {}", size_of::<u64>(), align_of::<u64>());

    println!(
        "Event  size {} align {} | kind @{} id @{} flags @{}",
        size_of::<Event>(),
        align_of::<Event>(),
        offset_of!(Event, kind),
        offset_of!(Event, id),
        offset_of!(Event, flags)
    );
    println!(
        "EventC size {} align {} | kind @{} id @{} flags @{}",
        size_of::<EventC>(),
        align_of::<EventC>(),
        offset_of!(EventC, kind),
        offset_of!(EventC, id),
        offset_of!(EventC, flags)
    );
    println!("[Event; 4]  = {} bytes", size_of::<[Event; 4]>());
    println!("[EventC; 4] = {} bytes", size_of::<[EventC; 4]>());
}
u8  size 1 align 1
u16 size 2 align 2
u32 size 4 align 4
u64 size 8 align 8
Event  size 8 align 4 | kind @6 id @0 flags @4
EventC size 12 align 4 | kind @0 id @4 flags @8
[Event; 4]  = 32 bytes
[EventC; 4] = 48 bytes

The fields add up to 7 bytes. #[repr(C)] follows the C rules and keeps declaration order. It leaves 3 bytes empty after kind so that id lands on a multiple of 4, then pads 2 more bytes at the end, for 12 bytes. The Rust Reference defines size as always a multiple of alignment, because the next element of an array must also start at an aligned address.

The default layout (repr(Rust)) reordered the fields to id, flags, kind, which cut the padding to 1 byte. What the Reference guarantees for the default layout is roughly that each field is aligned and fields do not overlap; the order is up to the compiler. The offsets above are simply what rustc 1.94.1 chose. In a 4-element array the gap grows to 16 bytes. Reach for #[repr(C)] only when memory is shared with another language or code depends on the byte layout, and leave the rest to the compiler.

Enums — a tag tells the variants apart

An enum with data carries a tag that picks the variant plus room for its largest variantShape — 24B (one cell 8B)Pointtag+padunusedunusedCircle(r)tag+padr: f64unusedRect(w, h)tag+padw: f64h: f64Option<u32> — 8B (one cell 4B)Some(v)tag+padv: u32Nonetag+padunusedThe compiler picks the cell order; only the sizes are measured

An enum with data holds a tag that says which variant it currently is, plus room for its largest variant. Some enums, though, need no tag at all.

use std::mem::size_of;
use std::num::NonZeroU32;

#[allow(dead_code)]
enum Shape {
    Point,
    Circle(f64),
    Rect(f64, f64),
}

#[allow(dead_code)]
enum List {
    Cons(i32, Box<List>),
    Nil,
}

fn main() {
    println!("Shape               = {}", size_of::<Shape>());
    println!("u32                 = {}", size_of::<u32>());
    println!("Option<u32>         = {}", size_of::<Option<u32>>());
    println!("NonZeroU32          = {}", size_of::<NonZeroU32>());
    println!("Option<NonZeroU32>  = {}", size_of::<Option<NonZeroU32>>());
    println!("&u64                = {}", size_of::<&u64>());
    println!("Option<&u64>        = {}", size_of::<Option<&u64>>());
    println!("Option<Box<u64>>    = {}", size_of::<Option<Box<u64>>>());
    println!("Option<bool>        = {}", size_of::<Option<bool>>());
    println!("String              = {}", size_of::<String>());
    println!("Option<String>      = {}", size_of::<Option<String>>());
    println!("List                = {}", size_of::<List>());
}
Shape               = 24
u32                 = 4
Option<u32>         = 8
NonZeroU32          = 4
Option<NonZeroU32>  = 4
&u64                = 8
Option<&u64>        = 8
Option<Box<u64>>    = 8
Option<bool>        = 1
String              = 24
Option<String>      = 24
List                = 16

Shape needs 16 bytes for the two f64s in Rect plus a tag, 24 bytes in total. The tag and its padding take 8 bytes because the following f64 must start at a multiple of 8. For the same reason Option<u32> adds a tag and padding, 4 bytes, to the 4-byte u32 and ends up at 8.

References, NonZero, and Box never hold 0, so None is stored as that value with no tagenums that keep the inner size, no tag (one cell 4B)Option<&u64>address 8B0 means NoneOption<NonZeroU32>value 4B0 means NoneLink::MoreBox 8BLink::Empty0Box is never null, so 0 marks Empty. RawLink(usize) is 16B

Option<NonZeroU32>, Option<&u64>, and Option<Box<u64>> are the same size as the type they wrap. A NonZeroU32 is never 0, and references and Box are never null. The compiler uses that value the type never holds (a niche) to mean None. The std docs for Option guarantee that for &U, &mut U, Box<U>, NonZero*, and a few others, Option<T> has the same size and alignment as T, and call this the null pointer optimization.

Option<bool> being 1 byte appears to work the same way. A bool only uses 0 and 1, so any other value is free to mean None. Option<bool> and Option<String> matching the size of what they wrap is not in the std docs’ list of guarantees; it is what this version measured.

The List from the smart pointers post was 16 bytes. Cons is a 4-byte i32, 4 bytes of padding, and an 8-byte Box. That size alone cannot tell whether Nil is stored as a 0 in the Box or as a tag in the padding, so I compared it with enums that hold a usize instead of a Box.

use std::mem::size_of;

#[allow(dead_code)]
enum List {
    Cons(i32, Box<List>),
    Nil,
}

#[allow(dead_code)]
enum RawList {
    Cons(i32, usize),
    Nil,
}

#[allow(dead_code)]
enum Link {
    More(Box<u64>),
    Empty,
}

#[allow(dead_code)]
enum RawLink {
    More(usize),
    Empty,
}

fn main() {
    println!("List    = {}", size_of::<List>());
    println!("RawList = {}", size_of::<RawList>());
    println!("Link    = {}", size_of::<Link>());
    println!("RawLink = {}", size_of::<RawLink>());
}
List    = 16
RawList = 16
Link    = 8
RawLink = 16

List and RawList are both 16 bytes, so no difference shows: a tag fits in the 4 bytes of padding after the i32. Without padding, Link and RawLink split. A usize uses 0 as a real value, so RawLink gets a tag and grows to 16 bytes, while Link, holding a Box, stays at 8 with no tag. Empty is stored as 0, a value a Box never holds.

Sizes of references and containers

Reference and container sizes come down to a few 8-byte cells: pointer, length, capacityone cell = 8B&u64ptr&strptrlenBox<[u64]>ptrlenVec<u64>ptrcaplenStringptrcaplenRc<u64>ptrRefCell<u64>borrow statevalueMutex<u64>24B (layout varies by platform)Cell order is not guaranteed. Sizes measured on aarch64-apple-darwin

References and standard containers range from 8 to 24 bytes. Carrying a length, a capacity, or extra state makes them larger.

use std::cell::RefCell;
use std::mem::size_of;
use std::rc::Rc;
use std::sync::{Arc, Mutex};

fn main() {
    println!("&u64         = {}", size_of::<&u64>());
    println!("&[u64]       = {}", size_of::<&[u64]>());
    println!("&str         = {}", size_of::<&str>());
    println!("Box<u64>     = {}", size_of::<Box<u64>>());
    println!("Box<[u64]>   = {}", size_of::<Box<[u64]>>());
    println!("Vec<u64>     = {}", size_of::<Vec<u64>>());
    println!("String       = {}", size_of::<String>());
    println!("Rc<u64>      = {}", size_of::<Rc<u64>>());
    println!("Arc<u64>     = {}", size_of::<Arc<u64>>());
    println!("RefCell<u64> = {}", size_of::<RefCell<u64>>());
    println!("Mutex<u64>   = {}", size_of::<Mutex<u64>>());
}
&u64         = 8
&[u64]       = 16
&str         = 16
Box<u64>     = 8
Box<[u64]>   = 16
Vec<u64>     = 24
String       = 24
Rc<u64>      = 8
Arc<u64>     = 8
RefCell<u64> = 16
Mutex<u64>   = 24

&[u64] and &str are fat pointers that include a length, so they are 16 bytes, and so is Box<[u64]>. Vec and String add a capacity for 24. Rc and Arc keep their counts on the heap next to the value, which leaves only an 8-byte pointer on the stack. RefCell<u64> puts an 8-byte slot for the borrow state beside the value. The 24 bytes of Mutex<u64> come from this platform’s lock implementation and may differ on other targets.

Vec and String — 24 bytes on the stack, elements on the heap

Vec and String keep a 24-byte pointer, capacity, and length on the stack and the elements in a heap bufferstackheapids: Vec<u64>ptrcap 8len 501234freefreefreename: Stringptrcap 4len 4'r''u''s''t'up to len is in use, up to cap is allocated

The std docs describe a Vec as a pointer to a heap allocation, a length, and a capacity, without guaranteeing the field order. Length (len) is how many elements it holds now; capacity (cap) is how many it can hold without allocating again. A String is also a pointer, length, and capacity, with UTF-8 bytes in that buffer. A push when len == capacity allocates a new, larger buffer. I printed those moments as capacity changes.

fn main() {
    let mut ids: Vec<u64> = Vec::new();
    println!("new:  len {:<3} cap {}", ids.len(), ids.capacity());
    let mut grows = 0;
    for id in 0..100u64 {
        let before = ids.capacity();
        ids.push(id);
        if ids.capacity() != before {
            grows += 1;
            println!("push: len {:<3} cap {}", ids.len(), ids.capacity());
        }
    }
    println!("capacity changes while pushing 100: {grows}");

    let mut sized: Vec<u64> = Vec::with_capacity(100);
    let start_cap = sized.capacity();
    for id in 0..100u64 {
        sized.push(id);
    }
    println!("with_capacity(100): cap {} -> {}", start_cap, sized.capacity());

    let mut name = String::from("rust");
    println!("String: len {} cap {}", name.len(), name.capacity());
    name.push_str(" memory");
    println!("String: len {} cap {}", name.len(), name.capacity());
}
new:  len 0   cap 0
push: len 1   cap 4
push: len 5   cap 8
push: len 9   cap 16
push: len 17  cap 32
push: len 33  cap 64
push: len 65  cap 128
capacity changes while pushing 100: 6
with_capacity(100): cap 100 -> 100
String: len 4 cap 4
String: len 11 cap 11
Pushing 100 items onto Vec::new grows capacity from 4 by doubling, reallocating 6 times; with_capacity(100) never changespush onto Vec::new() — when capacity changedlen 1cap 4len 5cap 8len 9cap 16len 17cap 32len 33cap 64len 65cap 128push onto Vec::with_capacity(100)cap 100each change allocates a larger buffer and moves the elementswith_capacity: no change over 100 pushes

Vec::new() starts at capacity 0 and does not allocate. The first push allocated 4 slots, and after that capacity doubled every time it filled up. Pushing 100 items allocated 6 times, counting the first allocation, and a separate run of the same code with 1000 items allocated 9 times. with_capacity(100) reserved 100 slots once up front and its capacity never changed. The std docs say Vec guarantees no particular growth strategy, so starting at 4 and doubling is this version’s behavior. When the String went from 4 bytes to needing 11, it allocated the 11 it needed rather than double to 8.

SmallVec — small ones stay off the heap

SmallVec keeps up to 4 elements inside itself and allocates a heap buffer on the 5th push, moving the elementspush 1-4 — inline (0 heap allocations)tags: SmallVec<[u32; 4]> (32B, stack)1234push 5 — spill (1 heap allocation)tags: SmallVec<[u32; 4]> (32B, stack)heap ptrlen 5heap12345freefreefree

Even a Vec that only ever holds three or four elements pays one heap allocation on its first push. The smallvec crate’s SmallVec<[T; N]> keeps up to N elements inside itself and moves them to the heap when it overflows, which is called spilling.

use smallvec::SmallVec;
use std::mem::size_of;

fn main() {
    println!("Vec<u32>           = {} bytes", size_of::<Vec<u32>>());
    println!("SmallVec<[u32; 4]> = {} bytes", size_of::<SmallVec<[u32; 4]>>());

    let mut tags: SmallVec<[u32; 4]> = SmallVec::new();
    for tag in 1..=5 {
        tags.push(tag);
        println!("push {tag}: len {} cap {} spilled {}", tags.len(), tags.capacity(), tags.spilled());
    }
}
Vec<u32>           = 24 bytes
SmallVec<[u32; 4]> = 32 bytes
push 1: len 1 cap 4 spilled false
push 2: len 2 cap 4 spilled false
push 3: len 3 cap 4 spilled false
push 4: len 4 cap 4 spilled false
push 5: len 5 cap 8 spilled true

spilled() reports whether the elements have moved to a separate heap buffer. It stayed false up to 4 elements and turned true on the fifth push, when the data moved to a heap buffer of capacity 8. In exchange, SmallVec itself is 8 bytes larger than Vec, and the inline slots take up space even when unused. It fits places where the element count usually stays at or below N; if it spills often, you get the larger size and the allocation anyway.

Arenas — allocate together, clear at once

Box::new allocates and frees once per node; Bump just advances a position in a chunk and clears it all on one resetBox::new × 1000 — 1000 allocs, 1000 freesglobal allocatornode 0node 1node 2node 3Bump::alloc × 1000 — only a position moveschunk (allocated up front)node 0node 1node 2node 3…next slotone reset() moves the position back and clears it allno per-value free, and Drop of stored values never runs

Building tree or graph nodes one Box::new at a time costs one allocation and one free per node. An arena allocates a large block of memory (a chunk) up front and places values in it one after another. bumpalo’s Bump keeps one position inside the chunk; on each request it checks the remaining space and moves the position by the value’s size (a bump). There is no per-value free; reset() moves the position back to the start of the chunk, clearing everything at once. If the arena grew to several chunks, it keeps one and returns the rest to the global allocator.

use bumpalo::Bump;
use std::mem::size_of;

struct Node {
    id: u64,
    weight: u64,
}

impl Drop for Node {
    fn drop(&mut self) {
        println!("drop node {}", self.id);
    }
}

fn main() {
    let mut arena = Bump::new();
    let first = arena.alloc(Node { id: 1, weight: 10 });
    let second = arena.alloc(Node { id: 2, weight: 20 });
    let gap = (second as *const Node as usize).abs_diff(first as *const Node as usize);
    println!("weight sum = {}", first.weight + second.weight);
    println!("gap = {gap} bytes, size_of::<Node>() = {}", size_of::<Node>());

    arena.reset();
    println!("after reset");

    let boxed = Box::new(Node { id: 3, weight: 30 });
    drop(boxed);
    println!("end of main");
}
weight sum = 30
gap = 16 bytes, size_of::<Node>() = 16
after reset
drop node 3
end of main

The two nodes are 16 bytes apart, exactly the size of Node, so they sit back to back. alloc takes the arena by &self, a shared borrow, and returns a &mut Node tied to that borrow. reset() takes &mut self, so using a reference from the arena after reset() does not compile.

use bumpalo::Bump;

fn main() {
    let mut arena = Bump::new();
    let first = arena.alloc(1u64);
    arena.reset();
    println!("{first}");
}
error[E0502]: cannot borrow `arena` as mutable because it is also borrowed as immutable
 --> examples/arena_err.rs:6:5
  |
5 |     let first = arena.alloc(1u64);
  |                 ----- immutable borrow occurs here
6 |     arena.reset();
  |     ^^^^^^^^^^^^^ mutable borrow occurs here
7 |     println!("{first}");
  |                ----- immutable borrow later used here

That is E0502 from the references and borrowing post. Code that would read memory already handed back is rejected by the borrow rules.

drop node 1 and drop node 2 never appear in the output. The bumpalo docs state that Drop does not run for values allocated in the arena. Only node 3, built with Box, was dropped. If you put a value that needs cleanup into an arena, such as a file handle or a Vec, that cleanup never happens. Arenas suit values with nothing to free, such as integers and references.

Measuring allocation cost with criterion

So far allocation counts came from the code. To see what they cost in time, I used criterion. In a separate cargo project outside the blog repository, with the dependencies below, benches/alloc.rs compares three pairs.

[dependencies]
bumpalo = "3"
smallvec = "1"

[dev-dependencies]
criterion = "0.5"

[[bench]]
name = "alloc"
harness = false
use bumpalo::Bump;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use smallvec::SmallVec;

const IDS: u64 = 1000;
const GROUPS: u32 = 1000;
const NODES: u64 = 1000;

struct Node {
    id: u64,
    weight: u64,
}

fn vec_growth(c: &mut Criterion) {
    let mut group = c.benchmark_group("push 1000 u64");
    group.bench_function("Vec::new", |b| {
        b.iter(|| {
            let mut ids = Vec::new();
            for id in 0..IDS {
                ids.push(black_box(id));
            }
            ids
        })
    });
    group.bench_function("Vec::with_capacity", |b| {
        b.iter(|| {
            let mut ids = Vec::with_capacity(IDS as usize);
            for id in 0..IDS {
                ids.push(black_box(id));
            }
            ids
        })
    });
    group.finish();
}

fn small_groups(c: &mut Criterion) {
    let mut group = c.benchmark_group("1000 groups of 3 u32");
    group.bench_function("Vec", |b| {
        b.iter(|| {
            let mut total = 0;
            for g in 0..GROUPS {
                let mut tags: Vec<u32> = Vec::new();
                for t in 0..3 {
                    tags.push(black_box(g + t));
                }
                total += black_box(tags).len();
            }
            total
        })
    });
    group.bench_function("SmallVec<[u32; 4]>", |b| {
        b.iter(|| {
            let mut total = 0;
            for g in 0..GROUPS {
                let mut tags: SmallVec<[u32; 4]> = SmallVec::new();
                for t in 0..3 {
                    tags.push(black_box(g + t));
                }
                total += black_box(tags).len();
            }
            total
        })
    });
    group.finish();
}

fn nodes(c: &mut Criterion) {
    let mut group = c.benchmark_group("1000 nodes");
    group.bench_function("Box::new each", |b| {
        b.iter(|| {
            let mut all: Vec<Box<Node>> = Vec::with_capacity(NODES as usize);
            for id in 0..NODES {
                all.push(Box::new(Node { id: black_box(id), weight: id * 2 }));
            }
            all.iter().map(|n| n.id + n.weight).sum::<u64>()
        })
    });
    let mut arena = Bump::new();
    group.bench_function("Bump::alloc + reset", |b| {
        b.iter(|| {
            let mut all: Vec<&Node> = Vec::with_capacity(NODES as usize);
            for id in 0..NODES {
                all.push(arena.alloc(Node { id: black_box(id), weight: id * 2 }));
            }
            let sum = all.iter().map(|n| n.id + n.weight).sum::<u64>();
            drop(all);
            arena.reset();
            sum
        })
    });
    group.finish();
}

criterion_group!(benches, vec_growth, small_groups, nodes);
criterion_main!(benches);

black_box keeps the compiler from precomputing values or deleting allocations nobody uses. The first version built each group with collect() and only read its length, and 1000 three-element Vecs came out around 4 µs, faster than SmallVec. At a little over 4 ns per group it was hard to believe an allocation happened. I assumed the optimizer had removed the allocation for a Vec whose length was read and then thrown away, switched to push plus black_box(tags), and measured again. The arena case builds one Bump and calls reset() at the end of each iteration, so the cost of allocating the first chunk barely shows up in the measurement.

I ran cargo bench --bench alloc -- --measurement-time 10 three times. Each benchmark warms up for 3 seconds and then collects 100 samples over 10 seconds (per the run log). Other work was running on the same machine during the measurement, and the load average sat between 50 and 87. The numbers below are for this machine under this load; they do not mean another machine will show the same values.

ComparisonRun 1Run 2Run 3
Vec::new13.94 µs5.13 µs3.84 µs
Vec::with_capacity7.15 µs3.77 µs5.11 µs
1000 groups of 3, Vec141.94 µs61.73 µs58.12 µs
same, SmallVec18.07 µs9.04 µs3.85 µs
1000 nodes, Box::new58.95 µs116.15 µs29.18 µs
same, Bump7.03 µs17.74 µs2.97 µs

Each value is the middle of criterion’s time: [lower estimate upper] line, the estimated time per iteration. The criterion docs describe the outer two as the lower and upper bounds of a confidence interval.

In every run SmallVec and Bump were faster in line with the allocations they removed; the with_capacity gap was about the size of the noisepush 1000 u64Vec::new3.8 µsVec::with_capacity5.1 µs1000 groups of 3 elementsVec58.1 µsSmallVec<[u32; 4]>3.8 µs1000 nodesBox::new each29.2 µsBump + reset3.0 µsbar = estimate, line = confidence interval, scale per groupApple M4 Pro, rustc 1.94.1 --release, third run

Under that load the same benchmark varied several-fold between runs, so I looked at comparisons within a run rather than absolute values. In all three runs SmallVec was roughly 7 to 15 times faster than Vec, and Bump roughly 7 to 10 times faster than Box::new. In both pairs one side allocates and frees per group or per node and the other does not. with_capacity, on the other hand, was faster in runs 1 and 2 but slower in run 3, and in the run 3 chart the two confidence intervals overlap. Pushing 1000 items only goes from 9 allocations to 1, which may be small next to the time spent writing 1000 elements. This measurement could not separate that difference from the noise of the load.

Wrapping up

Event came out at 12 or 8 bytes depending on field order, and Option<u32> gained a tag while Option<&u64> stayed the size of a pointer. Size is decided by field sizes, alignment, and whether the type has a value it never uses. Allocation counts could be read from the code too, through capacity() and spilled(). The clear wins in the measurements came where SmallVec and Bump removed the allocation per group and per node; with_capacity, which took 9 allocations down to 1, showed no difference I could confirm under the same load. Before adding code that cuts allocations, count how many allocations it actually removes. The next post looks at handling this layout directly with unsafe, and what you take responsibility for in place of the compiler.

References