How smart is Rust on optimizing variables inside loops?

Rust's borrow rules forces people to write more functional programming style code. I recently tried to translate some Java code into Rust and encountered an issue of borrowing both as mutable and immutable. The reason was that I used the internal state of a struct while doing a loop inside a method of the struct. A simple fix is to get rid of those internal state variables and bring them into loops. So here comes my questions. How smart is Rust on optimizing variables inside loops? In my case, those are 3 medium sized collections with sizes around 2000 to 3000. And these are created a methods instead of as variables in the loop directly. Will Rust be smartly enough to reuse them when possible?

I don't believe there are any guarantees and that it depends more on LLVM than rustc, So I would measure and see on a case by case basis where it matters.

If you have a more concrete example, there may be other approaches around simultaneous immutable and mutable borrows of different parts of your struct.


It depends what is in the variables.

The variables themselves, the fact that something has been assigned to a variable, are optimized perfectly, and are basically zero cost. There's no difference how many variables you use. For trivial copyable types like integers and borrowed references, you can rely on the optimizer to be quite smart.

However, if content of the variables creates side effects, then the optimizer will be much more conservative about them. If a type implements Drop, then it will be dropped at the end of its scope as it should, and the optimizer won't change that. Creation and destruction of big collections is unlikely to be optimized out. Allocated capacity is unlikely to be magically reused if you don't explicitly code that yourself. There are some expressions where stdlib can be clever about avoiding unnecessary reallocations, but in general if you create and destroy a collection, that's exactly what will happen.


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.