Suppose we have a program in Rust that has many Vecs in memory. These are not changed after being created. And we want to reduce memory usage.
With into boxed slice, we can convert a Vec
into a boxed slice. Often just the into()
function will work if the type can be inferred. Boxed slices can lead to significant memory savings.
To begin, we have a program that introduces 2 structs. One of the structs has a Vec
, and the other struct
has an equivalent Box containing a slice.
struct
that stores a Vec
. The field "v" is a standard Rust Vec
.into_boxed_slice
on the Vec
to convert it to a boxed slice. The into()
function would work here too.for
-loop.struct ExampleVector { v: Vec<usize>, } struct Example { b: Box<[usize]>, } fn main() { // Create vector. let data = vec![10, 20, 30]; // Part 1: Create struct with vector. let example_vec = ExampleVector { v: data.clone() }; // Part 2: Create struct with boxed slice. let example = Example { b: data.into_boxed_slice(), }; // Part 3: Can use boxed slice like any other slice. for i in example.b.iter() { println!("b = {i}"); } }b = 10 b = 20 b = 30
In Rust, a Vec
requires 3 words (which is 24 bytes on most computers). This is the storage requirement that is not a separate heap allocation.
into_boxed_slice()
, excess capacity is removed, which may save much more memory.use std::mem; fn main() { // Use size_of on vector and boxed slice. println!("{}", mem::size_of::<Vec<usize>>()); println!("{}", mem::size_of::<Box<[usize]>>()); }24 16
For long-lived collections, consider converting Vecs to boxed slices for memory savings. If many struct
instances are created, boxed slices can lead to significant memory savings.