Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when Java Compiler sees many String concatenations in one line?

Suppose I have an expression in Java such as:

String s = "abc" + methodReturningAString() + "ghi" +                  anotherMethodReturningAString() + "omn" + "blablabla"; 

What's the behaviour of the Java's default JDK compiler? Does it just makes the five concatenations or there is a smart performance trick done?

like image 433
Guilherme Avatar asked Aug 18 '09 21:08

Guilherme


People also ask

What happens on string concatenation Java?

Concatenating Strings Using the concat() method − The concat() method of the String class accepts a String value, adds it to the current String and returns the concatenated value.

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 string concatenation create a new string in Java?

Since the String object is immutable, each call for concatenation will result in a new String object being created.

How many objects are created in string concatenation?

it will create two object one in constant pool and one in heap memory.


1 Answers

It generates the equivalent of:

String s = new StringBuilder("abc")            .append(methodReturningAString())            .append("ghi")            .append(anotherMethodReturningAString())            .append("omn")            .append("blablabla")            .toString(); 

It is smart enough to pre-concatenate static strings (i.e. the "omn" + "blablabla"). You could call the use of StringBuilder a "performance trick" if you want. It is definitely better for performance than doing five concatenations resulting in four unnecessary temporary strings. Also, use of StringBuilder was a performance improvement in (I think) Java 5; prior to that, StringBuffer was used.

Edit: as pointed out in the comments, static strings are only pre-concatenated if they are at the beginning of the concatenation. Doing otherwise would break order-of-operations (although in this case I think Sun could justify it). So given this:

String s = "abc" + "def" + foo() + "uvw" + "xyz"; 

it would be compiled like this:

String s = new StringBuilder("abcdef")            .append(foo())            .append("uvw")            .append("xyz")            .toString(); 
like image 177
Kip Avatar answered Oct 10 '22 07:10

Kip