I have quickly read over the Java8 String api documentation.
Now I am little curious about String.join() method to concat/join strings.
This kind of example has helped me to understand better, though:
//Old way:
String str1 = "John";
String str2 = "Doe";
String result = str1 + " " +str2;
//or by using str1.concat(str2);
//New way:
String result = String.join(" ", str1, str2);
Still, I don't understand which one should I use. Is there any performance or other differences between these two processes.
Any help would be greatly appreciated.
Doing N concatenations requires creating N new strings in the process. join() , on the other hand, only has to create a single string (the final result) and thus works much faster.
There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.
String join is significantly faster then concatenation.
concat() method takes only one argument of string and concatenates it with other string. + operator takes any number of arguments and concatenates all the strings.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With