10 个版本
0.3.5 | 2022年9月10日 |
---|---|
0.3.4 | 2022年7月17日 |
0.3.3 | 2021年1月26日 |
0.3.2 | 2020年8月2日 |
0.2.0 | 2018年11月8日 |
#95 在 内存管理 中
11,783 每月下载量
在 339 个 Crates 中使用 (通过 gfx-backend-vulkan)
32KB
425 行
Inplace it!
以低成本将小型数组放置在栈上!
为此付出的唯一代价是选择数组类型时基于请求数组的大小!这只是一个 match 和
call!
是什么?
这个 crate 是为了一个目的而创建的:在栈上分配小型数组。使用它的最简单方法是
use inplace_it::{inplace_or_alloc_array, UninitializedSliceMemoryGuard};
inplace_or_alloc_array(
150, // size of needed array to allocate
|mut uninit_guard: UninitializedSliceMemoryGuard<u16>| { // and this is consumer of uninitialized memory
assert_eq!(160, uninit_guard.len());
{
// You can borrow guard to reuse memory
let borrowed_uninit_guard = uninit_guard.borrow();
// Let's initialize memory
// Note that borrowed_uninit_guard will be consumed (destroyed to produce initialized memory guard)
let init_guard = borrowed_uninit_guard.init(|index| index as u16 + 1);
// Memory now contains elements [1, 2, ..., 160]
// Lets check it. Sum of [1, 2, ..., 160] = 12880
let sum: u16 = init_guard.iter().sum();
assert_eq!(sum, 12880);
}
{
// If you don't want to reuse memory, you can init new guard directly
let init_guard = uninit_guard.init(|index| index as u16 * 2);
// Memory now contains elements [0, 2, 4, ..., 318]
// Lets check it. Sum of [0, 2, 4, ..., 318] = 25440
let sum: u16 = init_guard.iter().sum();
assert_eq!(sum, 25440);
}
}
)
为什么?
因为栈上的分配(即放置变量)比在堆上通常分配要快得多。
更多信息!
您可以通过阅读 API 参考文档 获取更多详细信息,或创建一个 新问题 来提交错误报告、功能请求或只是提问。
发行说明
版本 | 说明 |
---|---|
0.3.5 | 删除无用的 FixedArray trait。 |
0.3.4 | 修复不稳定内建的不正确使用。 |
0.3.3 | 为从 Iterator 的简单放置提供了一些糖。 |
0.3.2 | 将未初始化内存的放置从 try_inplace_array 移动出来,以防止编译器进行优化。 |
0.3.1 | 使用精确大小的迭代器进行初始化。 |
0.3.0 |
|
0.2.2 | 为安全函数提供固定的删除正确性。现在不受信任的函数不会删除你的数据,而是安全函数正确地执行删除。 |