String.join() vs other string concatenation operations
String.join
relies on the class StringJoiner
which itself relies on an internal StringBuilder
to build the joined string.
So performance-wise it's much the same as using a StringBuilder
and appending to it, or using a chain of +
(which nowadays are converted to StringBuilder
operations by the compiler).
But the significance of String.join
is not as a general replacement for +
or String.concat
, but in being the "reverse operation" of a String.split
operation. It makes more sense in that context - when you have a bunch of strings that you want to join together using a delimiter - than as a replacement for concat
.
That is, to build an output like "a/b/c/d"
or "(a+b+c+d)"
when you have a
,b
,c
and d
in an array or a list, String.join
or a StringJoiner
would make the operation clear and readable.
str1 + " " + str2
is internally converted into:
StringBuffer tmp1 = new StringBuffer();
tmp1.append(str1);
tmp1.append(" ");
String tmp2 = tmp1.toString();
StringBuffer tmp3 = new StringBuffer();
tmp3.append(tmp2);
tmp3.append(str2);
String result = tmp3.toString();
str1.concat(str2)
will not produce the same result, as the space wont be present between the two strings.
join should be equivalent to
StringBuffer tmp1 = new StringBuffer();
tmp1.append(str1);
tmp1.append(" ");
tmp1.append(str2);
String result = tmp.toString();
and hence be faster.