Does Sun’s hotspot JIT compiler automatically apply “final” to Java local variables?
I've heard of this, but I can't find a definite online resource to confirm it
Background: a colleague likes to make his local variables final One of the reasons he did this was his performance My argument is that Java's hotspot just in time compiler will automatically detect invariant local variables and make them final variables. Therefore, there is no performance benefit in doing this on its own
Please note that I am not asking whether local variables are the ultimate good coding practice, because there are already many (non topic) so questions
Editor: mrhobo puts forward a good view on optimizing the bytecode of integer text I should give an example of the type of code I'm talking about. My question is:
Object doSomething(Foo foo) { if (foo == null) { return null; } final Bar bar = foo.getBar(); final Baz baz = this.bazMap.get(bar); return new MyObject(bar,baz); }
Do you think the same type of optimization will happen in this case because both bar and Baz are marked final? Or will hotspot automatically detect that they have not changed within the scope of the method and treat them as final?
Similar problems
> Declaring local variable as final in a loop
>The same question, but the answer is obtained through experience (by viewing class files), and there is no document reference
> Do javac or Hotspot automatically add ‘final’ as an optimisation of invariant variables?
>For example, the same problem with variables
> Inlining in Java
>The same problem with the method
> Does use of final keyword in Java improve the performance?
>For similar problems, there is no consensus on local variables
Solution
To understand why the final local variable is completely boring for the compiler, some background on how the compiler works will help Basically, the compiler does not operate on the source code (or bytecode) itself, but parses it into some intermediate representation (usually several different representations when applying optimization) Almost every compiler I know uses some form of static single assignment or short SSA as its intermediate representation
As the name says, SSA forms basically mean that each variable is assigned only once For clarity, suppose we have the following simple code snippet:
y = 4 x = 5 y = 6 z = x + y
In the SSA form, this looks similar to the following:
y_1 = 4 x_1 = 5 y_2 = 6 z_1 = y_2 + x_1
Then why should we do this? Because it makes many compiler optimizations easier (for example, seeing that the first write of y can be eliminated because we have never read it) is insignificant So, if you want, you might see this, because each variable is already the final variable of the compiler
PS: loops and branching do complicate this, but I don't want to discuss it too much there - the wiki article has a short explanation of how to solve these problems