First of all, let me just put a disclaimer against premature optimization. Unless you are reasonably sure this is going to be a hotspot in your program, just choose the construct that fits your program the best.
If you are reasonably sure, however, and want to have good control over the concatenation, just use a StringBuilder
directly. That's what the built-in concatenation operation does anyway, and there's no reason to assume that it's slow. As long as you keep the same StringBuilder
and keep appending to it, rather than risking creating several in a row (which would have to be "initialized" with the previously created data), you'll have proper O(n) performance. Especially so if you make sure to initialize the StringBuilder
with proper capacity.
That also said, however, a StringBuilder
is, as mentioned, what the built-in concatenation operation uses anyway, so if you just keep all your concatenations "inline" -- that is, use A + B + C + D
, rather than something like e = A + B
followed by f = C + D
followed by e + f
(this way, the same StringBuilder
is used and appended to throughout the entire operation) -- then there's no reason to assume it would be slow.
EDIT: In reply to your comment, I'd say that String.format
is always slower. Even if it appends optimally, it can't do it any faster than StringBuilder
(and therefore also the concatenation operation) does anyway, but it also has to create a Formatter
object, do parsing of the input string, and so on. So there's more to it, but it still can't do the basic operation any faster.
Also, if you look internally in how the Formatter
works, you'll find that it also (by default) uses a StringBuilder
, just as the concatenation operation does. Therefore, it does the exact same basic operation -- that is, feeding a StringBuilder
with the strings you give it. It just does it in a far more roundabout way.