想必大家在需要字符串连接操作的时候最容易想到使用+操作符,如:
public String getAllContent(String[] str) {
String result = "";
for (int i = 0; i < str.length; i++) {
result += str[i];
}
return result;
}
以上代码如果str长度相当大的时候会出现严重的性能问题,因为String是不可变的字符串,每次相加的时候都会新创建一个新的String对象,这里可以使用StringBuilder来代替,如果是在多线程的环境下操作请使用StringBuffer,因为StringBuffer是线程安全的。