当前位置: 首页 > >

【java】数组、arraylist、linkedlist随机访问和遍历性能比较

发布时间:

取的MAX=10,100,1000,10000,100000,发现容量越大,数组的性能优势越加明显,linkedlist直接跑不动了。。



package CompareArray;

import java.util.ArrayList;
import java.util.LinkedList;

public class ArrayCmp {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
long start,end;
final int MAX = 100000;
int arr[]=new int[MAX];
ArrayList arraylist = new ArrayList<>();
LinkedList linklist = new LinkedList<>();
/*初始化各个数组链表*/
for (int i=0;i {
arr[i]=i;
arraylist.add(i);
linklist.add(i);
}
/*随机访问测试*/
System.out.println("随机访问测试("+MAX+"):");
start = System.nanoTime();
int tmp;
for (int i=0;i tmp = arr[i];
end = System.nanoTime();
System.out.println("数组: "+(end-start));
start = System.nanoTime();
for (int i=0;i tmp=arraylist.get(i);
end = System.nanoTime();
System.out.println("arraylist: "+(end-start));
start = System.nanoTime();
for (int i=0;i tmp=linklist.get(i);
end = System.nanoTime();
System.out.println("linkedlist: "+(end-start));
/*遍历测试*/
System.out.println("遍历测试("+MAX+"):");
start=System.nanoTime();
for (int e:arr)
tmp=e;
end = System.nanoTime();
System.out.println("数组: "+(end-start));
start = System.nanoTime();
for (int e:arraylist)
tmp=e;
end = System.nanoTime();
System.out.println("arraylist: "+(end-start));
start = System.nanoTime();
for (int e:linklist)
tmp=e;
end = System.nanoTime();
System.out.println("linkedlist: "+(end-start));
}

}



随机访问测试(10):
数组: 1359
arraylist: 47100
linkedlist: 35779
遍历测试(10):
数组: 906
arraylist: 373632
linkedlist: 380878
随机访问测试(100):
数组: 3171
arraylist: 30796
linkedlist: 103711
遍历测试(100):
数组: 4982
arraylist: 70651
linkedlist: 52082
随机访问测试(1000):
数组: 26267
arraylist: 375444
linkedlist: 5963617
遍历测试(1000):
数组: 46195
arraylist: 551616
linkedlist: 403069
随机访问测试(10000):
数组: 313851
arraylist: 3584601
linkedlist: 126547968
遍历测试(10000):
数组: 422091
arraylist: 4154333
linkedlist: 3639853
随机访问测试(100000):
数组: 3918832
arraylist: 11302702
linkedlist: 13882815925
遍历测试(100000):
数组: 453
arraylist: 925701
linkedlist: 1396703







友情链接: