Java字符串拼接的几种写法和效率
字符串拼接
第一种方式 使用+
String s1="abc";
String s2="def";
String s3=s1+s2;
注意: 使用 + 拼接字符串,底层都会创建一个 StringBuilder 实例调用 append() 方法来拼接。
来看一下一下两种+拼接字符串的性能
有三个字符串s1,s3,s3,将三个字符出拼接后返回
第一种:
public static String concat(String s1, String s2, String s3) {
String result = "";
result += s1;
result += s2;
result += s3;
return result;
}
第二种
public static String concat(String s1, String s2, String s3) {
return s1 + s2 + s3 ;
}
比较两种方式的性能:如果执行一万次
很明显第二种方式更优
对于第一种方式: 三个语句,每调用一次 + 就要new一个StringBuilder对象,那么第一种方式就要new三次StringBuilder
对于第二种方式: 只new一次StringBuilder即可
第二种方式 使用String.concat()
String s1="abc";
String s2="def";
String s3=s1.concat(s3);
底层代码是转换成byte[],然再new String(bytes,coder);
concat比+快
第三种方式 使用StringBuilder.append
String s1="abc";
String s2="def";
StringBuffer s3 = new StringBuffer(s1);
s3.append(s2);
三种方式性能比较
StringBuilder.append(s) > String.concat(s) > +