java LinkedList ArrayList 隨機訪問效率 list.get(int index)

來源:互聯網
上載者:User

理論上來說,肯定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無關。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.