Into boxed slice. 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.
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
Memory use. 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.
And A boxed slice requires just 2 words (16 bytes). So we save 8 bytes or 1 word per boxed slice.
Further When we create a boxed slice by calling into_boxed_slice(), excess capacity is removed, which may save much more memory.
Thus When we convert Vecs to boxed slices, we give up some features, but save memory.
Finally This can lead to better memory locality and improved performance in Rust programs.
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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 11, 2023 (new example).