Java中提供了三种字符串拼接的方法:+、concat()以及append()方法。通过比较 append()速度最快,concat()次之,+ 最慢。原因请看下面分析:
+ 方式拼接字符串
编译器对+进行了优化,它是使用StringBuilder的append()方法来进行处理的,编译器使用append()方法追加后要同toString()转换成String字符串,也就说 str +=”b”等同于str = new StringBuilder(str).append(“b”).toString();
它变慢的关键原因就在于new StringBuilder()和toString()
concat()方法拼接字符串
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = new char[count + otherLen];
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
}
这是concat()的源码,它看上去就是一个数字拷贝形式,我们知道数组的处理速度是非常快的,但是由于该方法最后是这样的:return new String(0, count + otherLen, buf);这是它变慢的根本原因。
append()方法拼接字符串
public AbstractStringBuilder append(String str) {
if (str == null) str = "null";
int len = str.length();
if (len == 0) return this;
int newCount = count + len;
if (newCount > value.length)
expandCapacity(newCount);
str.getChars(0, len, value, count);
count = newCount;
return this;
}
这是append()的源码,StringBuffer的append()方法是直接使用父类AbstractStringBuilder的append()方法。
与concat()方法相似,它也是进行字符数组处理的,加长,然后拷贝,但它最后是返回并没有返回一个新串,而是返回本身。