into_boxed_slice ExampleCreate boxed slices from vectors with into_boxed_slice. Understand the memory savings from boxed slices.
This page was last reviewed on May 11, 2023.
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.
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.
Part 1 We create an instance of the struct that stores a Vec. The field "v" is a standard Rust Vec.
Part 2 We use into_boxed_slice on the Vec to convert it to a boxed slice. The into() function would work here too.
Part 3 We can use a boxed slice much like a vector, although we cannot push elements to it or remove elements. Here we use a 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
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.
size of
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 11, 2023 (new example).
© 2007-2024 Sam Allen.