Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of into_boxed_slice() methods?

Looking at the methods available for Vec<T> I stumbled across

into_boxed_slice(self) -> Box<[T]>

String also has such a method (into_boxed_str(self)). The usefulness of having Deref for Vec<T>/String that allows them to be treated like a shared slice (&[T]) is obvious, but I don't see any use for an owned slice (Box<[T]>) except, perhaps, FFI. The Rust GitHub repo only uses into_boxed_slice() in a handful of cases.

Since methods for creating boxed slices are available in std and this container is listed on its main page, I thought that I might be missing something useful about it. What are cases where I should use an owned slice in favor of a Vec<T> or a String?

like image 754
ljedrz Avatar asked Sep 21 '16 11:09

ljedrz


1 Answers

The big reason for using into_boxed_slice() is that a boxed slice takes up only as much memory as:

  • The underlying data itself
  • A length field that gives the total length of the data

When using a standard Vec it is possible, and common, for the Vec to obtain more memory than what it actually needs to avoid having to allocate more memory every time a new element is added. That space is essentially unused. You can find out how much extra memory is being used by comparing Vec::len() versus Vec::capacity().

The main place that I have found the into_boxed_slice() function useful is in an in-memory file cache. I load the file into memory using a Vec for simplicity, but once the file is loaded, I no longer need to add or remove elements. So I convert it to a boxed slice using into_boxed_slice(). There would be other ways to achieve the same thing, but in this case the single function call is easier. I like the boxed slice type (as opposed to a Vec) because it clearly signals the intent that the cached file is not meant to modified.

Note: you can actually still use a Vec without the extra overhead by calling Vec::shrink_to_fit(), which will remove the extra allocated elements from the Vec.

like image 150
Nick Stevens Avatar answered Oct 16 '22 23:10

Nick Stevens