aspose file tools*
The moose likes Performance and the fly likes Compiler optimization of final variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Performance
Bookmark "Compiler optimization of final variables" Watch "Compiler optimization of final variables" New topic
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
Sheriff

Joined: Aug 22, 2010
Posts: 3610
    
  60

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Compiler optimization of final variables