小段代码求优化
我的一个程序里有个方法比较耗时,
调试发现是new string比较耗时间,
比如以下代码
public static void main(String[] args) {
long start = System.currentTimeMillis();
byte[] bytes = { 1, 2, 3, 4 };
byte[] target = new byte[1024 * 1024];
int currentIndex = 0;
for (int i = 0; i < 10000000; i++) {
if(currentIndex + 2 > target.length){
byte[] newTarget = new byte[target.length * 3 / 2];
System.arraycopy(target, 0, newTarget, 0, currentIndex);
target = newTarget;
}
System.arraycopy(bytes, 2, target, currentIndex, 2);
currentIndex += 2;
}
String str = new String(target, 0, currentIndex);
System.out.println(str.length());
long end = System.currentTimeMillis();
System.out.println(end - start);
}
StringBuilder sb = new StringBuilder();
long start = System.currentTimeMillis();
byte[] bytes = {1,2,3,4};
String string=null;
byte[] des = new byte[2];
for (int i = 0; i < 100000; i++) {
System.arraycopy(bytes, 2, des, 0, 2);
string =Arrays.toString(des);
sb.append(string);
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
byte[] tmp = new byte[tmpLength];
System.arraycopy(buff,0,tmp,0,size);
buff=tmp;
}
System.arraycopy(bytes, 2, buff, size, contentSize);
size +=contentSize;
}
String result = new String(buff,0,size);
return result;
}