Java中StringBuilder和String运行速率比较
编程时,若字符串改变的操作较多时,使用StringBuilder,效率会大大提高。下面两段代码实现的功能是一样的,但运行速率相差较大
//String 7ms 37.3MB
public String countAndSay(int n) {
String ori="1",stemp="";
int num=0,i=0,j=0;
char ctemp='1';
for(i=1;i<n;i++){
for(j=0;j<ori.length();j++){
if(j!=0&&ori.charAt(j)!=ctemp){
stemp+=String.valueOf(num)+ctemp;
num=0;
}
ctemp=ori.charAt(j);
num++;
}
ori=stemp+String.valueOf(num)+ctemp;
stemp="";
num=0;
}
return ori;
}
//StringBuilder 2ms 35.5MB
public String countAndSay(int n){
StringBuilder ori=new StringBuilder("1"),stemp=new StringBuilder("");
int num=0,i=0,j=0;
char ctemp='1';
for(i=1;i<n;i++){
for(j=0;j<ori.length();j++){
if(j!=0&&ori.charAt(j)!=ctemp){
stemp.append(num);
stemp.append(ctemp);
num=0;
}
ctemp=ori.charAt(j);
num++;
}
ori.delete(0,ori.length());
ori.append(stemp);
ori.append(num);
ori.append(ctemp);
stemp.delete(0,stemp.length());
num=0;
}
return ori.toString();
}