数组与集合性能比较
数组与集合性能比较
数组与集合性能比较,集合对数据结构进行优化分类成:ArrayList、Map等等,那他们与基本类型的数组性能如何呢。看理论还不如时间一波:读、写两方面。
写入性能比较
public class ArrayTest {
public static void main(String[] args) {
// 对jvm、cup进行预热
int temp=0;
for (int i=0;i<1000000;i++){
temp+=i;
}
System.out.println(temp);
String[] arr = new String[1000000];
Collection<String> coll = new ArrayList<>();
long start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
arr[i] = i + "";
}
System.out.println("数组100w赋值耗时:" + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
coll.add(i + "");
}
System.out.println("集合100w赋值耗时:" + (System.currentTimeMillis() - start));
}
}
结果:
1783293664
数组100w赋值耗时:39
集合100w赋值耗时:44
不管先后,正常写入还是基本类型的性能快
读取性能比较
public class ArrayTest02 {
public static void main(String[] args) {
// 对jvm、cup进行预热
int temp = 0;
for (int i = 0; i < 1000000; i++) {
temp += i;
}
System.out.println(temp);
String[] arr = new String[1000000];
Collection<String> coll = new ArrayList<>();
long start = 0;
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
coll.add(i + "");
}
System.out.println("集合100w赋值耗时:" + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
arr[i] = i + "";
}
System.out.println("数组100w赋值耗时:" + (System.currentTimeMillis() - start));
List<String> read = new ArrayList<>();
read.add("5");
read.add("999999");
read.add("439999");
read.add("666666");
start = System.currentTimeMillis();
for (String find : read)
if(coll.contains(find)){
temp++;
}
System.out.println("集合100w随机读取耗时:" + (System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (String find : read)
for (int i = 0; i < arr.length; i++) {
if (find.equals(arr[i])) {
temp++;
break;
}
}
System.out.println("数组100w随机读取耗时:" + (System.currentTimeMillis() - start));
}
}
结果一:
1783293664
集合100w赋值耗时:50
数组100w赋值耗时:59
集合100w随机读取耗时:15
数组100w随机读取耗时:13
结构二:
1783293664
集合100w赋值耗时:47
数组100w赋值耗时:61
数组100w随机读取耗时:16
集合100w随机读取耗时:15
不难看出,先后执行与jvm、CPU的调度有关,不管怎样,都是基本数组性能优先,毕竟集合底层就是数组实现
结论
数据量100w级看不出性能差距,可以选择集合存放,因为有大量接口方法,方便调用。
对性能斤斤计较
的可以选择基础类型数组。