into_boxed_slice() 方法有什么用? [英] What is the use of into_boxed_slice() methods?

查看:28
本文介绍了into_boxed_slice() 方法有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看可用于 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?

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() 来了解使用了多少额外内存.

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 而没有额外开销,这将从 中删除额外分配的元素>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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆