divinites
divinites

Reputation: 109

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?

Upvotes: 3

Views: 514

Answers (3)

Shepmaster
Shepmaster

Reputation: 430821

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..

Upvotes: 8

Matthieu M.
Matthieu M.

Reputation: 299890

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

Upvotes: 3

Sebastian Redl
Sebastian Redl

Reputation: 71989

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

Upvotes: 2

Related Questions