Your premise “that using the "+" concatenation operator for building strings is very inefficient”, is not correct. First, string concatenation itself is not a cheap operation, as it implies creating a new string containing all concatenated strings, hence, needing to copy the character contents. But this does always apply, regardless of how you do it.
When you use the +
operator, you’re telling what you want to do, without saying how to do it. Not even the Java Language Specification demands a particular implementation strategy, except that the concatenation of compile-time constants must be done at compile time. So for compile-time constants, the +
operator is the most efficient solution1.
In practice, all commonly used compilers from Java?5 to Java?8 generate code using a StringBuilder
under the hood (before Java?5, they used StringBuffer
). This applies to statements like yours, so replacing it with a manual StringBuilder
use would not gain much. You could be slightly better than the typical compiler generated code by providing a reasonable initial capacity, but that’s all.
Starting with Java?9, compilers generate an invokedynamic
instruction which allows the runtime to provide the actual code performing the concatenation. This could be a StringBuilder
code similar to the one used in the past, but also something entirely different. Most notably, the runtime provided code can access implementation specific features, which the application code could not. So now, the string concatenation via +
can be even faster than StringBuilder
based code.
Since this applies to a single concatenation expression only, when performing a string construction using multiple statements or even a loop, using a StringBuilder
consistently during the entire construction may be faster than the multiple concatenation operations. However, since the code runs in an optimizing environment, with a JVM recognizing some of these patterns, not even that can be said for sure.
This is the time to remember the old rule, to only try to optimize performance, when there is an actual problem with the performance. And always verify with impartial measuring tools, whether an attempted optimization truly improves the performance. There are a lot of widespread myths, wrong or outdated, about performance optimization tricks.
1 except you have repeated parts and want to reduce the size of the class file