1.字符串连接操作符"+",不适合用在大规模字符串连接场合,由于字符串不可变,2个字符串连接在一起时,它们内容都要被拷贝。
测试代码:
public class _51StringConcatenation {
private static final int NUM_ITEMS = 5000;
private static final String LINE_FOR_ITEM = "DJLKFLDLJKFKJLDKJFKJDKFLKDLKL" +
"LKJFLKDLKFLKJDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDLKKFDFDJFKLKLDFDFKDF";
/**
* @param args
*/
public static void main(String[] args) {
statement();
statement2();
String result = statement3();
System.out.println(NUM_ITEMS*LINE_FOR_ITEM.length() == result.length());
}
private static String statement(){
String result = "";
long start = System.currentTimeMillis();
for(int i=0;i<NUM_ITEMS;i++){
result += LINE_FOR_ITEM;
}
System.out.println("String concatention Using Time:"+(System.currentTimeMillis() - start));
return result;
}
private static String statement2(){
StringBuilder result = new StringBuilder();
long start = System.currentTimeMillis();
for(int i=0;i<NUM_ITEMS;i++){
result.append(LINE_FOR_ITEM);
}
System.out.println("String Builder Using Time:"+(System.currentTimeMillis() - start));
return result.toString();
}
private static String statement3(){
StringBuilder result = new StringBuilder(NUM_ITEMS*LINE_FOR_ITEM.length());
long start = System.currentTimeMillis();
for(int i=0;i<NUM_ITEMS;i++){
result.append(LINE_FOR_ITEM);
}
System.out.println("String Builder When Allocat Size Using Time:"+(System.currentTimeMillis() - start));
return result.toString();
}
}
打印结果:
String concatention Using Time:35172
String Builder Using Time:47
String Builder When Allocat Size Using Time:0
true
具有初始大小StringBuilder性能最好,其次StringBuilder,“+”号连接最差,
测试jdk1.6测试,jdk1.6在编译时,已经把"+"号连接转换成StringBuilder,不知道为何性能还是这么差