Memory management 我怎样才能延缓生锈';内存自动管理?

Memory management 我怎样才能延缓生锈';内存自动管理?,memory-management,rust,Memory Management,Rust,Rust开发了一个聪明的内存管理系统,但我有以下情况: loop { let mut example = Very_Complicated_Struct::new(); // very complicated data structure created dealing_with(&mut example); } // End of scope, so Rust is supposed to automatically drop the // memory of

Rust开发了一个聪明的内存管理系统,但我有以下情况:

loop {
    let mut example = Very_Complicated_Struct::new();
    // very complicated data structure created

    dealing_with(&mut example);
}
// End of scope, so Rust is supposed to automatically drop the
// memory of example here, which is time consuming

time_demanding_steps();

// But I want Rust to drop memory here,
// after the time_demanding_steps()

Rust中是否有这样做的方法?

您可以在循环外部创建一次结构,然后在每次迭代中清除它


Rust会在堆栈上分配这样的变量,所以它不能无限期地添加它们,否则会导致堆栈溢出。(另外,清除内存的速度非常快;如果Drop实现有很多内部内容(如VEC和字符串)要释放,那么它的运行速度可能会很慢。)

有两个潜在的修复方法:

  • 回收利用
  • 拖延
在高性能系统中,通过简单地重用同一对象(及其所有分配的内存),回收可以帮助避免所有的丢弃/创建迭代;然而,如果不小心,这可能意味着信息从一个用途泄漏到下一个用途

拖延要简单得多,虽然没有那么快。在您的情况下,需要使用
Vec
延迟销毁:

let mut delayed_destruction = vec!();

loop {
    let mut example = Very_Complicated_Struct::new();
    // very complicated data structure created

    dealing_with(&mut example);

    // Will be destroyed later.
    delayed_destruction.push(example);
}


time_demanding_steps();

// Destruction occurs here
使用a也可能是一种解决方案

let arena = Arena::new()

loop {
    let example = arena.alloc(Very_Complicated_Struct::new());
    dealing_with(example);
}

time_demanding_steps();

// Arena and all contained values are dropped
您必须遵守一些限制,尤其是您不会直接拥有该结构这一事实;您只会得到一个
&mut T


这是“垃圾桶”模式的特例。

所以我们手动创建一个“垃圾桶”来解决这个问题?如果我们使用不安全的函数,如libc::malloc和libc::free,该怎么办?在单个值的情况下,垃圾持有者可能只是
选项
?@divinite:与垃圾持有者效果相同,效率更低,更痛苦:)@Kroltan:实际上,这可能是一种
延迟销毁。Rust跟踪变量的移入/移出,因此允许未初始化的变量,只要它能证明它们将由使用点初始化。我在对代码进行基准测试时完全采用了“垃圾持有者”技巧。如果您提前知道循环的大小,您可以使用该容量分配
Vec
,避免在内部循环中重新分配。