A Rust ledger keeps a Vec<PaymentEvent> where only the rare Chargeback variant holds a 520-byte Evidence struct; why does every element take 528 bytes, and how do you shrink it?
answer
- every value fits the largest variant
- tag plus alignment padding
- Vec stores values inline
- Clippy large_enum_variant
- box the rare big payload
basics
~20 sAn enum value is as large as its largest variant plus the tag, rounded up to its alignment, so every element pays for Chargeback. Boxing the payload, Chargeback(Box<Evidence>), keeps one pointer inline and drops the enum to 24 bytes.
solid answer
~40 sEvery value of an enum must be able to hold any variant, so `size_of::<PaymentEvent>()` is the largest payload, the 520-byte `Evidence`, plus the tag, padded to the 8-byte alignment: 528. A `Vec` stores values inline, so a million heartbeats occupy 528 MB, and every move of an event copies 528 bytes. Clippy's `large_enum_variant` lint, warn-by-default in its `perf` group, flags an enum whose largest variant is more than 200 bytes bigger than the second-largest, and suggests `Chargeback(Box<Evidence>)`. With the box, the inline payload is an 8-byte pointer, the largest remaining variant is `Captured` at 16 bytes, and the enum is 24 bytes on rustc 1.99.1 for a 64-bit target. The cost moves to the rare case: one heap allocation per chargeback and a pointer to follow when reading it.
code
rust · 27 lines#![allow(dead_code)] // the variants are never built; only their sizes matter here
use std::mem::size_of;
struct Evidence { case_id: u64, documents: [u8; 512] }
enum PaymentEvent {
Heartbeat,
Authorized(u64),
Captured { order_id: u64, amount_cents: u64 },
Chargeback(Evidence), // rare, but sets the size of every value
}
enum PaymentEventBoxed {
Heartbeat,
Authorized(u64),
Captured { order_id: u64, amount_cents: u64 },
Chargeback(Box<Evidence>), // one pointer inline, the 520 bytes on the heap
}
fn main() {
println!("Evidence {}", size_of::<Evidence>());
println!("PaymentEvent {}", size_of::<PaymentEvent>());
println!("PaymentEventBoxed {}", size_of::<PaymentEventBoxed>());
let n = 1_000_000;
println!("1M events: {} vs {} bytes",
n * size_of::<PaymentEvent>(), n * size_of::<PaymentEventBoxed>());
}go deeper
Recall that an enum value is at least as large as its biggest variant, whichever variant it holds.
Explain the size as largest payload plus tag rounded to alignment, and show it with size_of before and after boxing.
Spot the oversized variant in a hot collection, measure it, use Clippy's large_enum_variant as a guard, and box only when the large case is rare.
Weigh memory and copy cost against allocation and indirection on the rare path, and decide whether large data belongs in the event at all or in a side store.
## How rustc sizes an enum An enum value must be able to hold whichever variant it is given, and it lives inline wherever it is stored: in a local, a struct field, a `Vec` slot. So its size is set by the **largest** variant, not by the one a value happens to hold: - take the largest variant's payload; - add room for the **tag** (the discriminant), unless the compiler can hide it in spare bit patterns of a payload; - round the total up to the enum's **alignment**, normally the largest alignment among its fields. For the ledger's enum: ```rust struct Evidence { case_id: u64, documents: [u8; 512] } // 520 bytes, align 8 enum PaymentEvent { Heartbeat, Authorized(u64), Captured { order_id: u64, amount_cents: u64 }, Chargeback(Evidence), } ``` `Evidence` is 520 bytes; the tag needs at least one byte, and alignment 8 rounds 521 up to **528**. A heartbeat, which carries nothing, still occupies 528 bytes. ## The ledger's numbers | Type (rustc 1.99.1, 64-bit) | `size_of` | |---|---| | `Evidence` | 520 | | `PaymentEvent` with `Chargeback(Evidence)` | 528 | | `PaymentEvent` with `Chargeback(Box<Evidence>)` | 24 | | one million events, inline payload | 528,000,000 bytes | | one million events, boxed payload | 24,000,000 bytes | ## Why it hurts - **Collections store values inline.** A `Vec<PaymentEvent>` of mostly heartbeats and authorisations pays 528 bytes a slot; so does a `VecDeque` or a `HashMap` value. - **Moves copy the whole value.** Passing an event by value, pushing it, or returning it is a byte copy of all 528 bytes, unless the optimiser elides that copy. - **Results and Options carry it too.** A function returning `Result<PaymentEvent, E>` returns a value at least that large on every call. - **Cache and stack pressure.** Fewer events fit in a cache line or a page, iteration touches more memory, and every stack frame holding one reserves the full size. - **It spreads.** `Option<PaymentEvent>` and any struct holding an event inherit the size. ## Finding it 1. Measure: `std::mem::size_of::<PaymentEvent>()` in a test or a scratch `main` gives the number for your target. 2. Run Clippy. Its `large_enum_variant` lint, in the warn-by-default `perf` group, reports "large size difference between variants" when the largest variant is more than 200 bytes bigger than the second-largest; that threshold is `enum-variant-size-threshold` in Clippy's configuration. On this enum it reports the 520-byte and 16-byte variants and suggests `Chargeback(Box<Evidence>)`. 3. For a whole crate's layouts, rustc's `-Z print-type-sizes` prints every type's size and padding, but it is an unstable flag that needs a nightly compiler. ## Fixing it **Box the large payload.** `Chargeback(Box<Evidence>)` stores one 8-byte pointer inline and the 520 bytes on the heap. The largest inline variant is now `Captured` at 16 bytes, so the enum is 24 bytes, and `Option<PaymentEvent>` stays 24 because the tag has spare values for `None`. The trade-offs: - one heap allocation and one free per chargeback; - one pointer to follow when reading the evidence; - moving a chargeback copies 24 bytes, not 528. Other options when boxing does not fit: - store the large data elsewhere, a side table or a database row, and keep only an id in the event; - shrink the payload itself, for instance a `Box<[u8]>` for variable-sized documents instead of a fixed 512-byte array. Boxing a variant to make a **recursive** enum possible at all is a different problem with its own lesson; here every type already compiles and the question is only how much space each value wastes. ## When not to box Boxing pays when the large variant is rare. If most events were chargebacks, boxing would add an allocation and an indirection to nearly every value for little memory saved. The judgment is a measurement, and a short review checklist covers it: 1. Is the enum stored in bulk (a `Vec`, a map, a channel buffer) or moved in a hot loop? If not, its size rarely matters. 2. How large is the gap between the largest and the second-largest variant? That gap is the space wasted by every value that is not the large variant. 3. How often does the large variant occur? Rare favours boxing; common favours leaving it inline or redesigning the data. 4. Does a benchmark or a memory profile confirm that the change helped?
- After boxing, does wrapping the event in an Option make it bigger again?Not on rustc 1.99.1: `Option<PaymentEvent>` with the boxed variant is still 24 bytes, because the four-variant tag has spare values and `None` takes one of them. Without the box, `Option<PaymentEvent>` is 528 bytes too, inheriting the full size. Reusing spare tag values is an optimisation rustc performs, not a documented guarantee.
- Clippy stays silent on an enum whose variants are 210 and 16 bytes; does that make it fine?Not necessarily. `large_enum_variant` fires only when the largest variant is more than 200 bytes bigger than the second-largest, so a 194-byte gap passes. Whether 211 bytes per value matters depends on how many values you store and move; `size_of` and a benchmark decide, not the lint's default threshold.
- When is boxing the big variant the wrong fix?When the big variant is common. Boxing then adds an allocation, a free and a pointer chase to most values while saving little memory. Keeping large data outside the event, an id into a side table, or shrinking the payload itself, may serve better.
A car park that sizes every bay for the coach that visits once a month wastes space on every car parked there. Boxing the large variant is sending the coach to an overflow lot and keeping only a ticket in its bay: every bay shrinks to car size, and the coach's driver walks a little further.
- An enum's size is the size of the variant the value currently holds.
- Rare variants cost nothing, since most values never use them.
- The tag adds one byte, so a 520-byte payload makes a 521-byte enum.
- Clippy flags every enum whose largest variant is over 200 bytes.
- Boxing a variant changes only its type; the enum size is unchanged.