| Author |
Compiler optimization of final variables
|
asabab mortanonov
Greenhorn
Joined: Nov 26, 2010
Posts: 2
|
|
Hi,
Can someone explain to me what optimizations respectively presumption the compiler makes on the following code?
When I disassembly this code, it is obviously that the compiler translates the string concatenation to StringBuilder.append() (yes, I know that strings are immutable)
Now if I change the class AsmMain so that all the variables are final:
... the disassembled output looks like this :
What is the explanation of this optimizations?
Thanks in advance.
|
 |
Martin Vajsar
Bartender
Joined: Aug 22, 2010
Posts: 2330
|
|
Java compiler automatically joins any String constants that are concatenated using the "+" operator. I believe this is defined by the JLS. String constants are String literals and all final String variables whose value is a String constant (yes, the definition is recursive).
Non-final String variables are not considered String constants, which is why in the first case the concatenation was not done.
|
 |
asabab mortanonov
Greenhorn
Joined: Nov 26, 2010
Posts: 2
|
|
Martin Vajsar wrote:Java compiler automatically joins any String constants that are concatenated using the "+" operator. I believe this is defined by the JLS. String constants are String literals and all final String variables whose value is a String constant (yes, the definition is recursive).
Non-final String variables are not considered String constants, which is why in the first case the concatenation was not done.
Hello Martin,
Thanks for the answer.After your hint I found it in JLS.
|
 |
 |
|
|
subject: Compiler optimization of final variables
|
|
|