`Option<Vec>` without freeing memory when setting to `None`

I have a struct member vector that might be presented and might not. The obvious choice is to put it behind Option.

But if I do that, when I'll set the option to None, I'll free the vector. The next time it will have to be re-allocated.

This is bad. I want to re-use the capacity from the previous time.

I can build a container that does that, but is there a built-in way to do this?

You can use Option::take() to get the old value of the vector and store it somewhere for reuse, and Vec::clear() to empty the vector without reducing its capacity.

1 Like

How do you plan on using the Vector?

1 Like

Exactly like the previous time; I process input and in some parts of it I need access to the vector.

I can also store the vector without Option and also store a boolean indicating whether the vector is accessible; However, I don't want to manually deal with storing/restoring the vector.

Have you considered having a different type for each state your algorithm can be in that only has the fields valid in that state?

Well, that’s the global allocator’s job; if you don’t like how it behaves, you either need to implement the alternative manually or find a crate that does.

This doesn't work this way. I don't have other data accessible for each state (then I could define an enum), but instead data that is always available and data that's available based on certain conditions (that may overlap).

I don't understand what you say, I replied to your idea:

And said that using this way I'll have to manually store the vector in a different field and keep track on where it's available.

@nologik, That's exactly why I said I can implement it myself but looking for a built-in way :smiley:

My point was that, aside from exceptional situations, giving the vector’s memory back to the allocator when you’re not using it and allocating a new one when you need it again is performant enough.

If your situation is one of the exceptional ones, it’s unreasonable to expect to not write at least some memory-management code specific to your use case. And writing a thin wrapper around a 2-field struct isn’t that much effort in the grand scheme of things.

1 Like

Got it :smiley:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.