ArrayList和LinkedList的幾種迴圈遍曆方式及效能對比分析(轉)

來源:互聯網
上載者:User

標籤:

主要介紹ArrayList和LinkedList這兩種list的五種迴圈遍曆方式,各種方式的效能測試對比,根據ArrayList和LinkedList的源碼實現分析效能結果,總結結論。通過本文你可以瞭解(1)List的五種遍曆方式及各自效能 (2)foreach及Iterator的實現 (3)加深對ArrayList和LinkedList實現的瞭解。閱讀本文前希望你已經瞭解ArrayList順序儲存和LinkedList鏈式的結構,本文不對此進行介紹。相關:HashMap迴圈遍曆方式及其效能對比 1. List的五種遍曆方式下面只是簡單介紹各種遍曆樣本(以ArrayList為例),各自優劣會在本文後面進行分析給出結論。(1) for each迴圈Java1234List list = new ArrayList();for (Integer j : list) {// use j} (2) 顯示調用集合迭代器Java1234List list = new ArrayList();for (Iterator iterator = list.iterator(); iterator.hasNext();) {iterator.next();}或Java12345List list = new ArrayList();Iterator iterator = list.iterator();while (iterator.hasNext()) {iterator.next();} (3) 下標遞增迴圈,終止條件為每次調用size()函數比較判斷Java1234List list = new ArrayList();for (int j = 0; j < list.size(); j++) {list.get(j);} (4) 下標遞增迴圈,終止條件為和等於size()的臨時變數比較判斷Java12345List list = new ArrayList();int size = list.size();for (int j = 0; j < size; j++) {list.get(j);} (5) 下標遞減迴圈Java1234List list = new ArrayList();for (int j = list.size() - 1; j >= 0; j--) {list.get(j);}在測試前大家可以根據對ArrayList和LinkedList資料結構及Iterator的瞭解,想想上面五種遍曆方式哪個效能更優。 2、List五種遍曆方式的效能測試及對比以下是效能測試代碼,會輸出不同數量級大小的ArrayList和LinkedList各種遍曆方式所花費的時間。ArrayList和LinkedList迴圈效能對比測試代碼PS:如果運行報異常in thread “main” java.lang.OutOfMemoryError: Java heap space,請將main函數裡面list size的大小減小。其中getArrayLists函數會返回不同size的ArrayList,getLinkedLists函數會返回不同size的LinkedList。loopListCompare函數會分別用上面的遍曆方式1-5去遍曆每一個list數組(包含不同大小list)中的list。print開頭函數為輸出輔助函數。 測試環境為Windows7 32位系統 3.2G雙核CPU 4G記憶體,Java 7,Eclipse -Xms512m -Xmx512m最終測試結果如下:1234567891011121314151617181920212223242526272829compare loop performance of ArrayList-----------------------------------------------------------------------list size | 10,000 | 100,000 | 1,000,000 | 10,000,000 -----------------------------------------------------------------------for each | 1 ms | 3 ms | 14 ms | 152 ms -----------------------------------------------------------------------for iterator | 0 ms | 1 ms | 12 ms | 114 ms -----------------------------------------------------------------------for list.size() | 1 ms | 1 ms | 13 ms | 128 ms -----------------------------------------------------------------------for size = list.size() | 0 ms | 0 ms | 6 ms | 62 ms -----------------------------------------------------------------------for j-- | 0 ms | 1 ms | 6 ms | 63 ms ----------------------------------------------------------------------- compare loop performance of LinkedList-----------------------------------------------------------------------list size | 100 | 1,000 | 10,000 | 100,000 -----------------------------------------------------------------------for each | 0 ms | 1 ms | 1 ms | 2 ms -----------------------------------------------------------------------for iterator | 0 ms | 0 ms | 0 ms | 2 ms -----------------------------------------------------------------------for list.size() | 0 ms | 1 ms | 73 ms | 7972 ms -----------------------------------------------------------------------for size = list.size() | 0 ms | 0 ms | 67 ms | 8216 ms -----------------------------------------------------------------------for j-- | 0 ms | 1 ms | 67 ms | 8277 ms -----------------------------------------------------------------------第一張表為ArrayList對比結果,第二張表為LinkedList對比結果。表橫向為同一遍曆方式不同大小list遍曆的時間消耗,縱向為同一list不同遍曆方式遍曆的時間消耗。PS:由於首次遍曆List會稍微多耗時一點,for each的結果稍微有點偏差,將測試代碼中的幾個Type順序調換會發現,for each耗時和for iterator接近。 3、遍曆方式效能測試結果分析(1) foreach介紹foreach是Java SE5.0引入的功能很強的迴圈結構,for (Integer j : list)應讀作for each int in list。for (Integer j : list)實現幾乎等價於Java1234Iterator iterator = list.iterator();while(iterator.hasNext()) {Integer j = iterator.next();}下面的分析會將foreach和顯示調用集合迭代器兩種遍曆方式歸類為Iterator方式,其他三種稱為get方式遍曆。這時我們已經發現foreach的一大好處,簡單一行實現了四行的功能,使得代碼簡潔美觀,另一大好處是相對於下標迴圈而言的,foreach不必關心下標初始值和終止值及越界等,所以不易出錯。Effective-Java中推薦使用此種寫法遍曆,本文會驗證這個說法。 使用foreach結構的類對象必須實現了Iterable介面,Java的Collection繼承自此介面,List實現了Collection,這個介面僅包含一個函數,源碼如下:Java123456789101112131415161718192021package java.lang; import java.util.Iterator; /** * Implementing this interface allows an object to be the target of * the "foreach" statement. * * @param the type of elements returned by the iterator * * @since 1.5 */public interface Iterable { /** * Returns an iterator over a set of elements of type T. * * @return an Iterator. */ Iterator iterator();}iterator()用於返回一個Iterator,從foreach的等價實現中我們可以看到,會調用這個函數得到Iterator,再通過Iterator的next()得到下一個元素,hasNext()判斷是否還有更多元素。Iterator源碼如下:Java1234567public interface Iterator { boolean hasNext(); E next(); void remove();} (2) ArrayList遍曆方式結果分析1234567891011121314compare loop performance of ArrayList-----------------------------------------------------------------------list size | 10,000 | 100,000 | 1,000,000 | 10,000,000 -----------------------------------------------------------------------for each | 1 ms | 3 ms | 14 ms | 152 ms -----------------------------------------------------------------------for iterator | 0 ms | 1 ms | 12 ms | 114 ms -----------------------------------------------------------------------for list.size() | 1 ms | 1 ms | 13 ms | 128 ms -----------------------------------------------------------------------for size = list.size() | 0 ms | 0 ms | 6 ms | 62 ms -----------------------------------------------------------------------for j-- | 0 ms | 1 ms | 6 ms | 63 ms -----------------------------------------------------------------------PS:由於首次遍曆List會稍微多耗時一點,for each的結果稍微有點偏差,將測試代碼中的幾個Type順序調換會發現,for each耗時和for iterator接近。從上面我們可以看出:a. 在ArrayList大小為十萬之前,五種遍曆方式時間消耗幾乎一樣b. 在十萬以後,第四、五種遍曆方式快於前三種,get方式優於Iterator方式,並且Java1234int size = list.size();for (int j = 0; j < size; j++) {list.get(j);}用臨時變數size取代list.size()效能更優。我們看看ArrayList中迭代器Iterator和get方法的實現Java1234567891011121314151617181920212223242526272829private class Itr implements Iterator {int cursor; // index of next element to returnint lastRet = -1; // index of last element returned; -1 if no suchint expectedModCount = modCount; public boolean hasNext() {return cursor != size;} @SuppressWarnings("unchecked")public E next() {checkForComodification();int i = cursor;if (i >= size)throw new NoSuchElementException();Object[] elementData = ArrayList.this.elementData;if (i >= elementData.length)throw new ConcurrentModificationException();cursor = i + 1;return (E) elementData[lastRet = i];}……} public E get(int index) {rangeCheck(index); return elementData(index);}從中可以看出get和Iterator的next函數同樣通過直接定位元據擷取元素,只是多了幾個判斷而已。c . 從上可以看出即便在千萬大小的ArrayList中,幾種遍曆方式相差也不過50ms左右,且在常用的十萬左右時間幾乎相等,考慮foreach的優點,我們大可選用foreach這種簡便方式進行遍曆。 (3) LinkedList遍曆方式結果分析1234567891011121314compare loop performance of LinkedList-----------------------------------------------------------------------list size | 100 | 1,000 | 10,000 | 100,000 -----------------------------------------------------------------------for each | 0 ms | 1 ms | 1 ms | 2 ms -----------------------------------------------------------------------for iterator | 0 ms | 0 ms | 0 ms | 2 ms -----------------------------------------------------------------------for list.size() | 0 ms | 1 ms | 73 ms | 7972 ms -----------------------------------------------------------------------for size = list.size() | 0 ms | 0 ms | 67 ms | 8216 ms -----------------------------------------------------------------------for j-- | 0 ms | 1 ms | 67 ms | 8277 ms -----------------------------------------------------------------------PS:由於首次遍曆List會稍微多耗時一點,for each的結果稍微有點偏差,將測試代碼中的幾個Type順序調換會發現,for each耗時和for iterator接近。從上面我們可以看出:a 在LinkedList大小接近一萬時,get方式和Iterator方式就已經差了差不多兩個數量級,十萬時Iterator方式效能已經遠勝於get方式。我們看看LinkedList中迭代器和get方法的實現Java12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152private class ListItr implements ListIterator {private Node lastReturned = null;private Node next;private int nextIndex;private int expectedModCount = modCount; ListItr(int index) {// assert isPositionIndex(index);next = (index == size) ? null : node(index);nextIndex = index;} public boolean hasNext() {return nextIndex < size;} public E next() {checkForComodification();if (!hasNext())throw new NoSuchElementException(); lastReturned = next;next = next.next;nextIndex++;return lastReturned.item;}……} public E get(int index) {checkElementIndex(index);return node(index).item;} /** * Returns the (non-null) Node at the specified element index. */Node node(int index) {// assert isElementIndex(index); if (index < (size >> 1)) {Node x = first;for (int i = 0; i < index; i++)x = x.next;return x;} else {Node x = last;for (int i = size - 1; i > index; i--)x = x.prev;return x;}}從上面代碼中可以看出LinkedList迭代器的next函數只是通過next指標快速得到下一個元素並返回。而get方法會從頭遍曆直到index下標,尋找一個元素時間複雜度為哦O(n),遍曆的時間複雜度就達到了O(n2)。所以對於LinkedList的遍曆推薦使用foreach,避免使用get方式遍曆。 (4) ArrayList和LinkedList遍曆方式結果對比分析從上面的數量級來看,同樣是foreach迴圈遍曆,ArrayList和LinkedList時間差不多,可將本例稍作修改加大list size會發現兩者基本在一個數量級上。但ArrayList get函數直接定位擷取的方式時間複雜度為O(1),而LinkedList的get函數時間複雜度為O(n)。再結合考慮空間消耗的話,建議首選ArrayList。對於個別插入刪除非常多的可以使用LinkedList。 4、結論總結通過上面的分析我們基本可以總結下:(1) 無論ArrayList還是LinkedList,遍曆建議使用foreach,尤其是資料量較大時LinkedList避免使用get遍曆。(2) List使用首選ArrayList。對於個別插入刪除非常多的可以使用LinkedList。(3) 可能在遍曆List迴圈內部需要使用到下標,這時綜合考慮下是使用foreach和自增count還是get方式。轉自:http://www.trinea.cn/android/arraylist-linkedlist-loop-performance/

ArrayList和LinkedList的幾種迴圈遍曆方式及效能對比分析(轉)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.