Sub topic 10
Avoiding unnecessary Box and dyn Trait
This chapter assumes you know ownership and lifetimes, traits and generics, and basic iterators. It builds on the earlier chapters on stack and heap storage and on measuring allocations.
What Box<dyn Trait> costs
Box::new(value) allocates on the heap when value has a nonzero size. Box<dyn Trait> adds two more costs:
- Each value is a separate allocation, so a
Vec<Box<dyn Trait>>of 1,000 items makes 1,000 allocations plus one for the vector. - Method calls go through a vtable (a table of function pointers). The compiler usually can't inline them.
Sometimes you need this. Recursive types and collections that hold many different types need indirection. Often you don't, and a cheaper form works.
Replace dyn with an enum when the set of types is closed
If you know every implementor, an enum stores the values inline and dispatches with a match.
trait Shape {
fn area(&self) -> f64;
}
struct Circle(f64);
struct Square(f64);
impl Shape for Circle {
fn area(&self) -> f64 {
3.14159 * self.0 * self.0
}
}
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
enum AnyShape {
Circle(Circle),
Square(Square),
}
impl Shape for AnyShape {
fn area(&self) -> f64 {
match self {
AnyShape::Circle(c) => c.area(),
AnyShape::Square(s) => s.area(),
}
}
}
fn total_boxed(shapes: &[Box<dyn Shape>]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn total_enum(shapes: &[AnyShape]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn main() {
let boxed: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Square(2.0))];
let inline = vec![AnyShape::Circle(Circle(1.0)), AnyShape::Square(Square(2.0))];
println!("{:.2} {:.2}", total_boxed(&boxed), total_enum(&inline));
}The enum version needs one allocation for the vector. The boxed version needs three. The trade-off is that adding a type means editing the enum. An enum is also as large as its largest variant, so one huge variant wastes space in every element.
Return impl Trait instead of Box<dyn Trait>
Returning a boxed iterator is a common habit. If the function returns one concrete type, impl Trait does the same job with no allocation.
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);
}impl Trait fails when different branches return different types. Boxing is the fix there, but Either from the either crate or an enum can also avoid the allocation.
Take generics or references as parameters
A function that only needs to call trait methods doesn't need ownership. Use a generic or a reference.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn report_generic<S: Shape>(s: &S) -> String {
format!("area {:.1}", s.area())
}
fn report_dyn(s: &dyn Shape) -> String {
format!("area {:.1}", s.area())
}
fn main() {
let sq = Square(3.0);
println!("{} / {}", report_generic(&sq), report_dyn(&sq));
}&dyn Shape is a reference plus a vtable pointer, so it allocates nothing. The generic version is compiled once per type, which allows inlining but grows the binary. Prefer &dyn when code size matters more than call speed.
Choosing a form
Common mistakes
- Boxing a type that is already a pointer, such as
Box<Vec<T>>orBox<String>. TheVecalready stores its data on the heap, so the extra box adds an allocation for nothing. - Writing
Box<dyn Fn(u32) -> u32>in a struct when a generic parameterF: Fn(u32) -> u32would work. - Boxing a large value only to avoid copying it. Moves are shallow copies, and the compiler often removes them.
Confirm any change with the counting allocator from the measurement chapter. Remove a Box only if the allocation count or a benchmark improves.
Exercise
A function returns Box<dyn Iterator<Item = String>>, and every code path returns the same kind of Filter<Lines<'_>, _> adapter. How can you remove the allocation, and what would stop you from doing so?
Show answer
Change the return type to impl Iterator<Item = String> and return the adapter directly. This works because there is one concrete type. It would stop working if different branches returned different iterator types, because impl Trait must resolve to a single type. In that case use an enum or Either, or keep the Box.