In the first example, msg
is in-scope at the outermost scope shown, while msg
is only in-scope in the loop body in the second example. Before I go on, I'll remind the reader that premature optimization, especially microoptimization as seen here, is not generally appropriate or useful and one should strive for clear, readable, and maintainable code above all.
I'll now continue for the curious reader. By compiling the code with javac
1.8.0_171 and disassembling with javap -c
, I get the following bytecode:
First approach:
Code:
0: aconst_null
1: astore_1
2: iconst_0
3: istore_2
4: iload_2
5: bipush 10
7: if_icmpge 19
10: ldc #2 // String f
12: astore_1
13: iinc 2, 1
16: goto 4
19: return
Second approach:
Code:
0: iconst_0
1: istore_1
2: iload_1
3: bipush 10
5: if_icmpge 17
8: ldc #2 // String f
10: astore_2
11: iinc 1, 1
14: goto 2
17: return
As you can see, the two compiled outcomes are materially very similar. Both have a loop structure, and the body of the loop consists of load constant (ldc) followed by astore_<n>
into a local variable slot. The assignment of variables to slots varies (first one assigns i
to slot 2 and msg
to 1, second does the opposite) but this should not have a significant effect. The first does include two extra bytecodes to store null
to msg
before the first iteration. However, the impact of this is so microscopic that it doesn't make sense to try to optimize this.
I don't currently have the toolset to view the resulting machine code from JIT optimizations, but I would strongly suspect that the entire loop would be optimized away by any capable JIT compiler.