Several writing methods and efficiency of Java string splicing
String splicing
The first way uses +
String s1="abc";
String s2="def";
String s3=s1+s2;
note:Using + to splice strings, the bottom layer will create a StringBuilder instance and call the append() method to splice.
Let's take a look at the performance of two + splicing strings
There are three strings s1, s3, and s3. After concatenating the three characters, it returns to the
first one:
public static String concat(String s1, String s2, String s3) {
String result = "";
result += s1;
result += s2;
result += s3;
return result;
}
The second
public static String concat(String s1, String s2, String s3) {
return s1 + s2 + s3 ;
}
Compare the performance of the two methods: if it is executed 10,000 times, the
second method is obviously better.
For the first method: three statements, each call + new StringBuilder object, then the first method requires newthree timesStringBuilder
for the second way: only newonceStringBuilder can
The second way uses String.concat()
String s1="abc";
String s2="def";
String s3=s1.concat(s3);
The underlying code is converted to byte[], and then new String(bytes,coder);
concat is faster than +
The third way to use StringBuilder.append
String s1="abc";
String s2="def";
StringBuffer s3 = new StringBuffer(s1);
s3.append(s2);
Performance comparison of three methods
StringBuilder.append(s) > String.concat(s) > +