I have a snippet of simple Java code:
public static void main(String[] args) {
String testStr = "test";
String rst = testStr + 1 + "a" + "pig" + 2;
System.out.println(rst);
}
Compile it with the Eclipse Java compiler, and examine the bytecode using AsmTools. It shows:
There are three local variables in the method. The argument is in slot 0, and slots 1 and 2 are supposedly used by the code. But I think 2 local variables are just enough — index 0 is the argument anyway, and the code needs only one more variable.
In order to see if my idea is correct, I edited the textual bytecode, reduced the number of local variables to 2, and adjusted some related instructions:
I recompiled it with AsmTools and it works fine!
So why don't Javac or the Eclipse compiler do this kind of optimization to use the minimal local variables?
Simply because Java gains performance from the just-in-time compiler.
What you do in Java source, and even what shows up in the class files isn't what enables performance at runtime. Of course you shouldn't neglect that part, but only in the sense of not making "stupid mistakes".
Meaning: the jvm decides at runtime if a method is worth translating into (highly optimized!) machine code. If the jvm decides "not worth optimising", why make javac more complex and slower by having a lot of optimization in there? Plus: the more simple and basic the incoming byte code, the easier it is for the JIT to analyze and improve that input!