As stated earlier, it is difficult to say with certainty which version of a code snippet will run faster simply by examining the source code. Code that runs faster on one compiler might run slower on another. The only way to be sure is to measure the execution time (which is what whodgson did in the first reply). However, you have to remember that those measurements only apply to that specific compiler and target computer.
For the record, a simple-minded compiler would
probably generate slower code for option #2 due to (a) more code inside the loop; (b) the code inside the loop includes a function call to the str::length method; and (c) the str::length method might traverse the string to compute the length. weaknessforcats has already pointed out that the compiler might replace the function call with inline code, cancelling out (b). The str object might contain an explicit length field, cancelling out (c). Notice that the snippet invokes the method for a built-in type -- this means that the compiler could conceivably have enough information to know it is safe to pull the method-call out of the loop, cancelling out (a).
By the way, aggressive optimization can be a great help for embedded software where processor-speed is often a limiting factor; but it can also pose great difficulties if it rearranges instructions that access memory-mapped registers. The typical way to protect accesses to memory-mapped registers is to use the
volatile keyword, but that may not always work:
Volatiles are miscompiled, and what to do about it.