• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Compiler optimization of final variables

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Sheriff
Posts: 3837
66
Netbeans IDE Oracle Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
The overall mission is to change the world. When you've done that, then you can read this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic