日期:2014-05-20  浏览次数:20742 次

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

比如以下代码
		StringBuilder sb = new StringBuilder();

long start = System.currentTimeMillis();
byte[] bytes = {1,2,3,4};
for (int i = 0; i < 100000; i++) {
String string = new String(bytes, 2, 2);
// String string = "test";
sb.append(string);
}
long end = System.currentTimeMillis();

System.out.println(end - start);


用new string的话要60毫秒,
而直接用test的话只要16毫秒,

问题是我必需从bytes中取得后面两位的数据, 前面两位没有用,
有什么办法优化吗?
------解决方案--------------------
StringBuilder sb = new StringBuilder();
 
        long start = System.currentTimeMillis();
        byte[] bytes = {1,2,3,4};
        String string=null;
        for (int i = 0; i < 100000; i++) {
            string = new String(bytes, 2, 2);
            sb.append(string);
        }
        long end = System.currentTimeMillis();
 
        System.out.println(end - start);

------解决方案--------------------
创建String对象放在for循环外,append 100000次就可以了
------解决方案--------------------
String string = new String(bytes, 2, 2); 
放在for外面,
还是说bytes每次不一样?
------解决方案--------------------
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();