Function side effects and optimizations
⚓ Rust 📅 2026-03-18 👤 surdeus 👁️ 1From the recent post in the other thread:
while i < s.len() {
That's idiomatic Rust; the compiler can very easily see that optimization opportunity. It should be done this way.
Can someone explain in some detail why that works in Rust, e.g. it makes no sense to declare a variable let l = s.len() and use that in the loop?
It is quite obvious, that it works when the method is inlined. But what is with a non inlined function and side effects -- e.g. when self is mutable, or when the parameter list is not empty? I assume that Rust's has an advantage for optimizations, as it typically forbids use of global state variables? For other languages, things are not that obvious, I can remember a case some years ago (Nim), where expressions like x = tiny_func() + 2 * tiny_func() resulted actually in two function calls. That time I even tried Nim's efect system, to indicate that the called function does not change global state, but that did not avoid the multiple function calls.
2 posts - 2 participants
🏷️ Rust_feed