String.join() vs other string concatenation operations

后端 未结 3 1787
时光取名叫无心
时光取名叫无心 2021-01-01 18:20

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

3条回答
  •  不思量自难忘°
    2021-01-01 18:45

    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.

提交回复
热议问题