Sub topic 10
Avoiding unnecessary Box and dyn Trait
This chapter assumes you know ownership and lifetimes, basic Vec, String and Box, traits and generics, and how to run cargo build and cargo bench. It also assumes you can count allocations with the counting allocator from the measurement chapter.
Box and dyn Trait are often written out of habit. Each Box::new of a non-zero-sized value is one heap allocation, and each call through a trait object is an indirect call the compiler usually cannot inline. This chapter shows when that cost is real, how to remove it, and when to keep it.
What Box and dyn actually cost
Box<T> moves a T to the heap and keeps a pointer on the stack. Box<dyn Trait> does the same, but the pointer is a fat pointer: it holds the data address and the address of a vtable (a table of function pointers for that concrete type).
use std::mem::size_of;
trait Shape {
fn area(&self) -> f64;
}
struct Circle {
r: f64,
}
fn main() {
println!("&Circle: {}", size_of::<&Circle>());
println!("Box<Circle>: {}", size_of::<Box<Circle>>());
println!("&dyn Shape: {}", size_of::<&dyn Shape>());
println!("Box<dyn Shape>: {}", size_of::<Box<dyn Shape>>());
}On a 64-bit target the first two lines print 8 and the last two print 16. The costs are:
- One allocation and one deallocation per boxed value.
- A pointer hop on every access, which hurts cache locality in a
Vec<Box<T>>. - An indirect call for each trait method, which blocks inlining.
A reference to a trait object, &dyn Trait, has the same fat pointer but allocates nothing. The trait object is not the cost on its own. The Box is.
A Box around a zero-sized value, such as Box::new(()) or a boxed unit struct, does not allocate.
When Box is the right tool
Do not remove a Box that the type system needs:
- Recursive types.
enum List { Cons(i32, Box<List>), Nil }has no finite size without indirection. - Values whose concrete type is chosen at run time and stored together, for example plugins loaded from configuration.
- Very large values you move often, where a pointer-sized move is cheaper than copying. Measure this first.
- Error paths.
Box<dyn Error>allocates only when an error occurs, which is usually off the hot path.
For the rest, there is usually a cheaper design.
Replace Vec of Box dyn with generics or an enum
The most common unnecessary boxing is Vec<Box<dyn Trait>> where every element has the same concrete type, or where the set of types is small and known.
use std::f64::consts::PI;
trait Shape {
fn area(&self) -> f64;
}
struct Circle {
r: f64,
}
struct Rect {
w: f64,
h: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
PI * self.r * self.r
}
}
impl Shape for Rect {
fn area(&self) -> f64 {
self.w * self.h
}
}
enum AnyShape {
Circle(Circle),
Rect(Rect),
}
impl Shape for AnyShape {
fn area(&self) -> f64 {
match self {
AnyShape::Circle(c) => c.area(),
AnyShape::Rect(r) => r.area(),
}
}
}
fn total_dyn(shapes: &[Box<dyn Shape>]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn total_static<S: Shape>(shapes: &[S]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn main() {
// Three allocations: the Vec buffer and one Box per element.
let boxed: Vec<Box<dyn Shape>> = vec![
Box::new(Circle { r: 1.0 }),
Box::new(Rect { w: 2.0, h: 3.0 }),
];
// One allocation: elements are stored inline in the Vec buffer.
let inline = vec![
AnyShape::Circle(Circle { r: 1.0 }),
AnyShape::Rect(Rect { w: 2.0, h: 3.0 }),
];
// One allocation, and the call to area() can be inlined.
let circles = vec![Circle { r: 1.0 }, Circle { r: 2.0 }];
println!("{:.3}", total_dyn(&boxed));
println!("{:.3}", total_static(&inline));
println!("{:.3}", total_static(&circles));
}The three styles trade off differently:
| Approach | Allocations for n items | Dispatch | Open to new types |
|---|---|---|---|
| `Vec<Box<dyn Trait>>` | n + 1 | Indirect, via vtable | Yes, any crate can add one |
| `Vec<Enum>` | 1 | `match`, inlinable | No, edit the enum |
| `Vec<T>` with `T: Trait` | 1 | Static, inlinable | One type per collection |
An enum is as large as its largest variant plus a tag. If one variant is much bigger than the rest, every element pays that size. Clippy's large_enum_variant lint flags this. Boxing only the rare large variant is a valid use of Box.
Return impl Trait instead of Box dyn Trait
Returning Box<dyn Iterator> or Box<dyn Fn> from a function allocates on each call. Since Rust 1.26, impl Trait in return position names the concrete type for the compiler without exposing it to callers.
fn evens_boxed(limit: u32) -> Box<dyn Iterator<Item = u32>> {
Box::new((0..limit).filter(|n| n % 2 == 0))
}
fn evens(limit: u32) -> impl Iterator<Item = u32> {
(0..limit).filter(|n| n % 2 == 0)
}
fn main() {
let a: u32 = evens_boxed(10).sum();
let b: u32 = evens(10).sum();
println!("{} {}", a, b);
}Both print the same sum. The second version allocates nothing, and the compiler can fuse the filter into the consuming loop.
impl Trait has a limit. A function body must return a single concrete type. If two if branches return different iterator types, impl Iterator fails to compile. You then have three options:
- Make both branches the same type, for example by using a
matchinside one adapter. - Write a small enum that implements
Iteratorby forwarding to its variants. - Accept a
Box<dyn Iterator>and confirm with a measurement that it matters.
Borrow the trait object instead of boxing it
A function that only needs to call a trait object for the duration of the call can take &dyn Trait or &mut dyn Trait. The caller keeps ownership, and nothing is allocated.
fn sum_all(items: &mut dyn Iterator<Item = u32>) -> u32 {
let mut total = 0;
for x in items {
total += x;
}
total
}
fn main() {
let mut a = (1..=4).map(|x| x * 2);
let mut b = vec![10u32, 20, 30].into_iter();
println!("{} {}", sum_all(&mut a), sum_all(&mut b));
}Here two different iterator types go through one non-generic function. You get dynamic dispatch, and the compiler emits one copy of the function instead of one per type.
Generic closures instead of Box dyn Fn
A struct field of type Box<dyn Fn(u32) -> bool> costs one allocation at construction and an indirect call per use. A generic parameter stores the closure inline.
struct BoxedFilter {
pred: Box<dyn Fn(u32) -> bool>,
}
struct Filter<F: Fn(u32) -> bool> {
pred: F,
}
impl<F: Fn(u32) -> bool> Filter<F> {
fn count(&self, data: &[u32]) -> usize {
data.iter().filter(|&&x| (self.pred)(x)).count()
}
}
fn main() {
let limit = 3;
let data = [1, 2, 3, 4, 5];
let boxed = BoxedFilter { pred: Box::new(move |x| x > limit) };
let inline = Filter { pred: move |x| x > limit };
println!("{}", data.iter().filter(|&&x| (boxed.pred)(x)).count());
println!("{}", inline.count(&data));
}A closure that captures nothing is zero-sized, so a Filter holding it adds no bytes of storage at all. A plain function pointer, fn(u32) -> bool, also needs no Box when you do not need captures.
Trade-offs of going static
Removing dyn is not free:
- Monomorphization copies the generic code for each concrete type. Many instantiations increase compile time and binary size, and can hurt the instruction cache.
- Generics spread through type signatures. A struct with a closure parameter forces that parameter onto every
impland every struct that contains it. - Enums close the set of types. Downstream crates cannot add variants.
dyn Traitlimits what a trait may contain. Generic methods and methods returningSelfneedwhere Self: Sizedto stay object safe.
A common compromise is a thin generic wrapper around a non-generic inner function that takes &dyn Trait. This limits how many copies the compiler produces.
Common errors
- Boxing by reflex. A
Box::newinside a hot loop, or aVec<Box<T>>whereVec<T>works, adds an allocation per element and gains nothing.Vec<T>already stores elements on the heap, so boxing each one adds a second indirection. - Boxing to avoid a large move. Moves of large values are
memcpycalls and are often optimized away. Measure before adding the pointer. - Replacing
dyneverywhere. Adyncall in cold code costs nothing noticeable. Removing it only adds generic complexity. - Assuming a
Box<dyn Error>is on the hot path. It allocates only when you return an error.
Exercise
A function builds a pipeline with fn pipeline(v: &[u32]) -> Box<dyn Iterator<Item = u32> + '_> { Box::new(v.iter().copied().filter(|x| x % 2 == 1)) } and is called once per request. Rewrite the signature to avoid the allocation, and say when the rewrite would not compile.
Show answer
Use fn pipeline(v: &[u32]) -> impl Iterator<Item = u32> + '_ { v.iter().copied().filter(|x| x % 2 == 1) } and drop the Box::new. The '_ is needed because the iterator borrows v. The rewrite would not compile if the body returned different iterator types from different branches, because impl Trait requires one concrete type. In that case, use one adapter chain, a small enum implementing Iterator, or keep the Box<dyn Iterator>.