Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Compiler String optimization

It seems reasonable to me that the compiler is going to take something like this:

log.info("A really long logger message that is kind of a pain in the tucous " + 
    "and violates formatting standards by making the line to long");

and compile the two Strings into one. I'm pretty sure this is true but I would like to have my ducks in a row if anyone brings it up.

like image 744
user447607 Avatar asked Dec 13 '12 17:12

user447607


People also ask

Does Java compiler optimize string concatenation?

As a consequence, a Java compiler is not required to optimize string concatenation, though all tend to do so as long as no loops are involved. You can check the extent of such compile time optimizations by using javap (the java decompiler included with the JDK).

Does the Java compiler optimize?

The JVMs JIT compiler is one of the fascinating mechanisms on the Java platform. It optimizes your code for performance, without giving away its readability. Not only that, beyond the “static” optimization methods of inlining, it also makes decisions based on the way that the code performs in practice.

Is string faster than StringBuilder?

Conclusion. StringBuilder executes significantly faster than the String class when performing the concatenation or modification operations. Modifying a String creates a new String in the heap memory. To change the content of the String, we should consider the StringBuilder class.


1 Answers

Yes, this will be handled by the constant expression part of the Java Language Specification. In particular see part 15.18.1. String Concatenation Operator +

like image 180
Jeff Foster Avatar answered Sep 28 '22 12:09

Jeff Foster