工作是遇到合并数组的问题,想到了两个方法。同事说利用System.arraycopy()方法晦涩难懂,没有用List转换来的清晰易懂。所以我就编写了两个方法区测试其性能。代码如下:
package com.lys.test;
import java.util.ArrayList;
import java.util.List;
public class TestCombineArrays {
public static void main(String[] args) {
String[] str1 = {"a","b","c"};
String[] str2 = {"a","b","c"};
String[] str3 = {"a","b","c"};
long start = System.currentTimeMillis();
for(int i=0;i<100000;i++){
String[] result1 = combineArrays1(str1,str2,str3);
}
long end = System.currentTimeMillis();
System.out.println("combineArrays1: cost time=="+(end-start));
long start1 = System.currentTimeMillis();
for(int i=0;i<100000;i++){
String[] result1 = combineArrays2(str1,str2,str3);
}
long end1 = System.currentTimeMillis();
System.out.println("combineArrays2: cost time=="+(end1-start1));
}
/**
* 利用List作中介合并
* @param info
* @return
*/
public static String[] combineArrays1(String[]... info){
List<String> list = new ArrayList<String>();
for(String[] arr:info){
for(String s:arr){
list.add(s);
}
}
String[] result = new String[list.size()];
for(int i=0;i<list.size();i++){
result[i] = list.get(i);
}
return result;
}
/**
* 利用System.arraycopy()方法
* @param info
* @return
*/
public static String[] combineArrays2(String[]... info){
int length = 0;
for(String[] arr:info){
length += arr.length;
}
String[] result = new String[length];
int index = 0;
for(String[] str:info){
System.arraycopy(str, 0, result, index, str.length);
index += str.length;
}
return result;
}
}
总的来说,利用List要比System.arraycopy方式更加耗费性能,所耗时间是其4倍之多。活到老学到老~
数组合并性能对比
本文通过实验对比了使用List和System.arraycopy方法合并多个数组的性能差异,发现利用List的方式虽然更易于理解,但性能上不如System.arraycopy方法。
1825

被折叠的 条评论
为什么被折叠?



