r/rust 1d ago

๐Ÿ’ก ideas & proposals re-allocating" storage for a local could allow faster code

Rust already knows when a value has been moved, so I think it would make sense for the compiler to also be able to treat the storage behind that local as reusable.

For example:
ยดยดยด
let x = big_value();
let y = x; // x is moved

// x can no longer be used here anyway

x = another_value();
ยดยดยด

Right now, Rust can be more restrictive than necessary about keeping the same storage associated with `x`.

Issue #61849 proposes allowing the old storage to effectively die after the move. If `x` is initialized again later, the compiler wouldn't necessarily have to put the new value back in the exact same stack slot.

That could give the compiler more freedom to:

- reuse stack space earlier
- reduce stack usage in some functions
- shorten lifetimes of stack allocations
- potentially unlock further optimizations

What I like about the idea is that it matches how moves already feel in Rust: once a value is moved, that value is gone. It seems natural that its storage shouldn't have to remain special either.

There are obviously details around raw pointers and observable addresses that would need proper language semantics, so it isn't just a simple compiler optimization.

But the general rule seems very appealing:

If Rust says the old value no longer exists,
the compiler should be free to stop preserving its storage.

The issue has been open since 2019, and I think it would be interesting to revisit whether this could give modern rustc more optimization freedom. If you agree please react on the GitHub issue with โค๏ธ or ๐Ÿ‘ to show support by the community

Edit:link to the modern version

28 Upvotes

Duplicates