Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Compiler optimization of final variables

 
asabab mortanonov
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic