Side note, don't fall into the trap of premature optimization. You'll more than likely end up shooting yourself in the foot for something that usually doesn't matter in most cases.
post
Functionally equivalent, the compiler will optimize lots for you. As the programmer, your focus should be on whether that variable is relevant to the loop's scope exclusively or not (i.e. if you need to access the variable after the loop has modified it). If not, keep it in the loop so that its easier to read your code.
I would say that they are equivalent. If I'm not mistaken, let statements only reserves space on the stack, and this only increments the stack register.
And on the latter snippet, the compiler would certainly not bother to modify the stack pointer as the type doesn't change.
Without context, there's no reason to compare the performance of these. The compiler is complex enough that what you do in the loop and after the loop matters with regards to optimizations.
Do you have more context? What's actually happening in the code?
The second one is more expensive as you constantly are creating a new variable. In the first one you just constantly change the value of a variable.
This is Rust not Python
They're both optimised out by the compiler. If you disable compiler optimisations, they're identical in machine code anyway, unless you introduce a second loop, in which case the first will be more memory efficient as the memory used in the first loop can be reused in the second loop, whereas if you declare the variable outside the loop it can't (again, without compiler optimisations, which make the whole comparison pointless).
all 13 comments