試了一下java中字符串連接的速度
package test;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int times = 100000;
String s1 = "";
String s2 = "";
StringBuffer s3 = new StringBuffer("");
long a = System.currentTimeMillis();
for(int i = 0 ;i < times ; i ++){
s1 += "a";
}
long b = System.currentTimeMillis();
for(int i = 0 ;i < times ; i ++){
s2 = s2.concat("a");
}
long c = System.currentTimeMillis();
for(int i = 0 ;i < times ; i ++){
s3.append("a");
}
long d = System.currentTimeMillis();
System.out.print((b-a) + "|" + (c-b) + "|" + (d-c));
}
}
毫無疑問stringbuffer的append肯定最快,但是按這個量級,結果是3931,1950,16
可見速度差距還是很大的,原因還是因爲string連接字符串的時候創建了很多對象,而stringbuffer則是對一個對象在內存中進行字符串追加