into_boxed_slice()方法有什么用? [英] What is the use of into_boxed_slice() methods?
问题描述
看着 Vec< T>
可用的方法,我偶然发现了
Looking at the methods available for Vec<T>
I stumbled across
into_boxed_slice(self) -> Box<[T]>
String
也有这样的方法( into_boxed_str(self)
)。为 Vec< T>
/ String
Deref 的有用性>可以将它们像共享切片(& [T]
)一样对待,但是我看不到拥有切片( Box< [T]>
),也许还有FFI。在少数情况下,Rust GitHub存储库仅使用 into_boxed_slice()
。
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.
因为创建盒装切片的方法是在 std
中可用,并且该容器在其主页上列出,我认为我可能会缺少一些有用的东西。在什么情况下我应该使用所有权切片来支持 Vec< T>
或 String
? p>
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
?
推荐答案
使用 into_boxed_slice()
的主要原因是盒装切片需要最多 尽可能多的存储空间:
The big reason for using into_boxed_slice()
is that a boxed slice takes up only as much memory as:
- 基础数据本身
- 一个
length
字段,它给出数据的总长度
- The underlying data itself
- A
length
field that gives the total length of the data
使用时标准的 Vec
可能并且很常见, Vec
获得的内存多于其实际需要避免的容量每次添加新元素时都必须分配更多的内存。该空间实际上是未使用的。通过比较 Vec :: len()
与 Vec :: capacity()$ c $,可以发现正在使用多少额外的内存。 c>。
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()
.
我发现 into_boxed_slice()
函数有用的主要地方是在内存中文件缓存。为了简单起见,我使用 Vec
将文件加载到内存中,但是一旦加载文件,就不再需要添加或删除元素。因此,我使用 into_boxed_slice()
将其转换为盒装切片。还有其他方法可以实现相同的目的,但是在这种情况下,单个函数调用会更容易。我喜欢盒装切片类型(而不是 Vec
),因为它清楚地表明了缓存文件无意修改的意图。
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.
注意:实际上,您仍然可以通过调用 Vec :: shrink_to_fit()$来使用
Vec
而没有额外的开销c $ c>,这将从 Vec
中删除额外分配的元素。
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
.
这篇关于into_boxed_slice()方法有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!