理論上來說,肯定LinkedList比ArrayList隨機訪問效率要低,然後LinkedList比ArrayList插入刪除元素要快。
突然想起之前寫一個日記本程式,是用LinkedList+Map索引,作為資料庫。Map記錄了LinkedList中每一個日記的index和日期之間的對應關係。從Map中擷取到某個日期對應日記的index,然後再去LinkedList,get(index)。
Integer a = 1;
LinkedList list = new LinkedList();
for (int i = 0; i < 2000000; i++) {
list.add(a);
}
System.out.println(list.size());
long start = System.nanoTime();
list.get(1000000);
long end = System.nanoTime();
System.out.println(end - start);
上邊一段代碼,看出了幾樣事情:
1.LinkedList的隨機訪問速度確實差點,大概用了17毫秒。下邊會貼出LinkedList隨機訪問的原始碼,也就是這裡為什麼選擇1000000中間數的原因。
2.Java棧區和堆區都是有限的,list那裡如果一次添加5000000個item就會記憶體溢出
(Exception in thread "main" java.lang.OutOfMemoryError: Java heap space)。
但有點奇怪,不是new了在記憶體堆區嗎?記憶體堆區也會爆~~
下邊是LinkedList隨機訪問的原始碼,採取了折半的遍曆方式,每個迴圈裡邊進行一次int的比較。
private Entry<E> entry(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: "+index+
", Size: "+size);
Entry<E> e = header;
if (index < (size >> 1)) {
for (int i = 0; i <= index; i++)
e = e.next;
} else {
for (int i = size; i > index; i--)
e = e.previous;
}
return e;
}
換了ArrayList的話,添加5000000個item都不會爆,但再大點,還是會爆~~
隨機訪問效率確實高很多,只需要16微秒左右,足足快了1千倍,而且跟get的index無關。