Using + to concat string in Java

concatenation, java, string

Solution

No. The compiler will perform the concatenation at compile time if all your strings are constant (as they are in your question). So that ends up performing better than the `StringBuilder` version.

It will use `StringBuilder` (or `StringBuffer`) to perform the concatenation of any non-constant parts otherwise.

So the compiled version of:

String x = "a" + "b";

should be exactly the same as:

String x = "ab";

Note that the "non-constant" parts can mean that you can sometimes get (very minor) extra efficiencies using bracketing wisely. For example:

int value = ...;
String x = "a" + value + "b" + "c";

... is less efficient than:

int value = ...;
String x = "a" + value + ("b" + "c");

... as the first appends `"b"` and `"c"` separately. The efficient version is equivalent tO:

int value = ...;
String x = "a" + value + "bc";

I can't remember ever seeing this used as a legitimate micro-optimization, but it's at least a point of interest.

Problem

I have a huge string as below : ``` String str = "aaaaaaa" + "bbbbbbbb" + "cccccccc" .... + "zzzzzzzz"; // about 200 lines long ``` Is it a big waste of memory? Will it be better to put it in one line or use `StringBuilder`? This is done to create a long sql.

Original source