This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android 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: 3606
    
  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
 
Similar Threads
Help with returning one string from three methods of type string?
string question
Number of String objects created
Overriding of Member variables
Diiference between String ,StringBuffer & StringBuilder