public class stringBuliderDem {
public static void main(String[] args) {
long time=TestTime(50000);
long times=TestTimes(50000);
System.out.println(time+"PK"+times);
}
public static long TestTime(int Num){
String s="";
long time=System.currentTimeMillis();
for(int i=0;i
s+="A";
}
long time1=System.currentTimeMillis()-time;
return time1;
}
public static long TestTimes(int Num){
StringBuilder s=new StringBuilder();
long time=System.currentTimeMillis();
for(int i=0;i
s.append("A");
}
long time1=System.currentTimeMillis()-time;
return time1;
}
}
输出:1116PK2
备注:Java中大量进行多行连加时,用StringBuilder进行,程序效率比较高,如果明确知道运算后字符串的长度,可以new StringBulider(NUM)中指定长度,可进一步优化程序。
分析:
s5=s1+s2+s3;被JAVA优化成s5=new StringBulider(s1).append(s2).append(s3).toString.只需创建一次StringBuilder.
s5+=s1;s5+=s2;s5+=s3;被Java优化成s5=new StringBuilder(s5).append(s1);s5=new StringBulider(s5).append(s2);s5=new StringBuilder(s5).append(s3);每次运算都会创建StringBuilder,运算完成后,被系统回收,大量此类操作,运算效率比较低,代码中具体体现