读书人

小段代码求优化,该如何处理

发布时间: 2013-01-06 15:44:47 作者: rapoo

小段代码求优化
我的一个程序里有个方法比较耗时,
调试发现是new string比较耗时间,

比如以下代码


[解决办法]
StringBuilder sb = new StringBuilder();

long start = System.currentTimeMillis();
char[] bytes = {1,2,3,4};
for (int i = 0; i < 100000; i++) {
sb.append(bytes, 2, 2);
}
long end = System.currentTimeMillis();

System.out.println(end - start);

只要5ms
int是可以直接当做char的
[解决办法]

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);
}


次数改成10000000了,你那个方法要2s多,这个600多ms
[解决办法]

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);

[解决办法]
/**
* @param sb
* @param bytes
*/
private static long foo3(StringBuilder sb, byte[] bytes) {
long start = System.currentTimeMillis();

for (int i = 0; i < 100000; i++) {
char[] chars = new char[40];
for (int j = 0; j < chars.length; j++) {
chars[j] = (char) bytes[j + 2];
}
sb.append(chars);

}
long end = System.currentTimeMillis();

return end - start;
}

如果byte[]是由中文字符串获取的,将byte直接转换为char是错误的做法,

private static String foo( byte[] bytes) {

int time = 100000;
int size = 0;
byte[] buff = new byte[time<<2];
for (int i = 0; i < time; i++) {
int contentSize = bytes.length-2;
if(buff.length-size<contentSize){
int tmpLength = buff.length;
while(tmpLength-size<contentSize){
tmpLength=tmpLength<<1;


}
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;

}

读书人网 >J2SE开发

热点推荐