Java LinkedList 与ArrayList性能对比

ArrayList的存储结构是数组,而LinkedList开始链状结构存zai的。在追加数据的时候,ArrayyList会涉及到扩容和数组的拷贝的问题,而LinkedList没有这个问题, 所以想当然以为ArrayList的效率会低于LinkedList。但是经过测试,结果不是这样的。

先看插入的效率

下边是测试代码,分别向ArrayList 、Vector和LinkedList 插入五百万条数据:

int TIMES= 5000000;
ArrayList arrayList = new ArrayList();
LinkedList linkedList = new LinkedList<>();
Vector vector = new Vector();

long bforetime =  new Date().getTime();
for (int i = 0; i < TIMES; i++) {
    arrayList.add("st" );
    //arrayList.add(0,"st" );
}
long aftertime =  new Date().getTime();
System.out.println(" arrayList 消耗的时间是 : " + (aftertime-bforetime));


bforetime =  new Date().getTime();
for (int i = 0; i < TIMES; i++) {
    vector.add("st" );
    //vector.add(0,"st" );
}
aftertime =  new Date().getTime();
System.out.println(" vector 消耗的时间是 : " + (aftertime-bforetime));


bforetime =  new Date().getTime();
for (int i = 0; i < TIMES; i++) {
  linkedList.add("st" );
    //linkedList.add(0,"st");
}
aftertime =  new Date().getTime();
System.out.println(" linkedList  消耗的时间是 : " + (aftertime-bforetime));

 

测试的结果如下:

 arrayList 消耗的时间是 : 111
 vector 消耗的时间是 : 296
 linkedList  消耗的时间是 : 3839

 

可以看到arrayList 的效率明显高于linkedList  ,与想当然的不一样。!!!

原因是ArrayList在添加元素的时候,只有在扩容的时候消耗资源拷贝,主要消耗在申请内存以及内存拷贝.的过程当中,但是由于每次扩容是1.5被,在上述代码的执行过程中ArrayList也不过是被扩容了33次左右。

而对于LinkedList来讲,每次都需要申请内存,源码为:final Node newNode = new Node<>(l, e, null); 这样需要五百万次的申请内存的操作,因而ArrayList的插入队尾的操作要远远的高于LinkedList。

再看看查找的效率

在上述的数据的基础之上,我们在做一个实验。代码如下:

bforetime =  new Date().getTime();
for (int i = 0; i < 20000 ; i++) {
    String s = arrayList.get(i*25);
}
aftertime =  new Date().getTime();
System.out.println(" Array 获取元素 消耗的时间是 : " + (aftertime-bforetime));

bforetime =  new Date().getTime();
for (int i = 0; i < 20000 ; i++) {
    String s = vector.get(i*25);
}
aftertime =  new Date().getTime();
System.out.println(" vector 获取元素 消耗的时间是 : " + (aftertime-bforetime));

最后的执行结果是:

 Array 获取元素 消耗的时间是 : 3
 vector 获取元素 消耗的时间是 : 3
 linkedList  获取元素 消耗的时间是 : 16120

按照索引序号去查找元素的速度ArrayList 是远远高于LinkedList的。

 

 

 

 

你可能感兴趣的:(java,Java,ArrayList,LinkedList,性能,比较)