简体   繁体   中英

How can I delay Rust's memory auto-management?

Rust developed a clever memory management system, but I have the following situation:

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()

Is there a way in Rust to do so?

Using a TypedArena may also be a solution.

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

There are a few limitations you have to adhere to, notably the fact that you won't own the structure directly; you only get a &mut T .

This is a specialized case of the "garbage holder" pattern described by Matthieu M. .

There are two potential fixes:

  • recycling
  • delaying

In high performance systems recycling can help avoiding all the drop/create iterations by simply reusing the same object (and all its allocated memory) in place; however if not done carefully it may means leaking information from one use to the next.

Delaying is much simpler, although not as fast. In your situation it would involve using a Vec to delay destruction:

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

You could create the struct outside the loop once and just clear it on every iteration.

Rust allocates variables like this on the stack, so it can't just add them indefinitely, or you'll get a stack overflow. (Also, getting rid of the memory is extremely fast; it's the Drop implementation running that is probably slow, if it has a lot of internal things like Vecs and Strings to deallocate.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM