Comparison and analysis of several cyclic traversal modes and performances of ArrayList and LinkedList (RPM)

Source: Internet
Author: User

Mainly introduces the ArrayList and LinkedList of the two list of the five kinds of loop traversal mode, various ways of performance test comparison, according to ArrayList and LinkedList source code implementation Analysis performance results, concluding conclusions. Through this article you can learn (1) The five traversal modes of the list and their respective performance (2) The implementation of foreach and iterator (3) to deepen the understanding of ArrayList and LinkedList implementations. Before reading this article, I hope you have understood the structure of ArrayList sequential storage and LinkedList chain, this article does not introduce this. Related: HashMap loop traversal mode and its performance comparison 1. The list of five ways to traverse the following is just a brief introduction of the various traversal examples (taking ArrayList as an example), the merits and demerits of each will be analyzed later in this article to give a conclusion. (1) for Each loop java1234list List = new ArrayList (); for (Integer j:list) {//Use J} (2) Displays the call set iterator Java1234list List = new ArrayList (); for (Iterator iterator = List.iterator (); Iterator.hasnext ();) {Iterator.next ();} or java12345list List = new ArrayList (); Iterator iterator = List.iterator (); while (Iterator.hasnext ()) {Iterator.next ();} (3) Subscript increment loop, termination condition for each call size () function comparison judgment java1234list List = new ArrayList (); for (int j = 0; J < List.size (); j + +) {List.get (j);} (4) Subscript increment loop, termination condition is equal to size () temporary variable comparison judgment java12345list List = new ArrayList (); Int size = List.size (); for (int j = 0; J < size; J + +) {List.get (j);} (5) Subscript descending cyclic java1234list List = new ArrayList (); for (int j = list.size ()-1; J >= 0; j--) {list.get (j);} Before the test can be based on the ArrayList and LinkedList data structure and iterator understanding, think of the above five ways of traversing which performance is better. 2. The performance test and comparison of the list five traversal methods The following is the performance test code, which outputs the time spent by different order sizes of ArrayList and linkedlist various traversal modes. ArrayList and LinkedList cycle performance comparison test code PS: If you run the report exception in the thread "main" Java.lang.OutOfMemoryError:Java heap space, put the main function inside the list Size is reduced. Where the Getarraylists function returns a different size of the Arraylist,getlinkedlists function returns the LinkedList of the different size. The Looplistcompare function iterates through the list of each list array (containing a list of different sizes) using the above traversal mode of 1-5 respectively. The print start function is the output helper function. Test environment for WINDOWS7 32-bit system 3.2G dual-core CPU 4G memory, Java 7,eclipse-xms512m- XMX512M final test results are as follows: 1234567891011121314151617181920212223242526272829compare Loop performance of ArrayList-----------------------------------------------------------------------List Size | 10,000 | 100,000 | 1,000,000 | 10,000,000-----------------------------------------------------------------------for each | 1 ms | 3 MS | Ms | Ms-----------------------------------------------------------------------for Iterator | 0 ms | 1 ms | Ms | Ms-----------------------------------------------------------------------for list.size () | 1 ms | 1 ms | Ms | Ms-----------------------------------------------------------------------for size = List.size () | 0 ms | 0 ms | 6 ms | Ms-----------------------------------------------------------------------for j--| 0 ms | 1 ms | 6 ms | 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 | Ms | 7972 ms-----------------------------------------------------------------------for size = List.size() | 0 ms | 0 ms | Ms | 8216 ms-----------------------------------------------------------------------for j--| 0 ms | 1 ms | Ms | 8277 Ms-----------------------------------------------------------------------The first table is the ArrayList comparison result, The second table is the result of linkedlist comparison. Table horizontal is the same traversal way of the time consumption of the list traversal of different size, vertical for the same list of different traversal mode of time consumption. PS: Because the first traversal of the list takes a little more time, the result of the for each is slightly biased, and several type order switches in the test code are found to be time-consuming and for iterator close. 3, Traverse mode performance Test results analysis (1) foreach Introduction foreach is a very powerful loop structure introduced by Java SE5.0, and for (Integer j:list) should be read as the for each int in list. The for (Integer j:list) implementation is almost equivalent to Java1234iterator iterator = List.iterator (); while (Iterator.hasnext ()) {Integer j = Iterator.next ();} The following analysis classifies the foreach and display call collection iterators as iterator, and the other three are called get-way traversal. At this point we have found a great advantage of foreach, a simple line to achieve the function of four lines, so that the code is simple and beautiful, another great advantage is relative to the subscript loop, foreach does not have to care about subscript initial value and termination value and out of bounds, so it is not easy to error. This is the recommended way to use this notation in Effective-java, which this article validates. The class object using the foreach struct must implement the Iterable interface, and Java's collection inherits from this interface, and the list implements the collection, which contains only one function, The source code is as follows: Java123456789101112131415161718192021package Java.lang; Import Java.util.Iterator; /** * Implementing this interface allows a 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 () is used to return a iterator, as we can see from the equivalent implementation of foreach, that the function is called to get the iterator, and then the next element is obtained by iterator next (), and Hasnext () determines if there are more elements. Iterator source code is as follows: Java1234567public interface Iterator {Boolean hasnext (); E next (); void Remove (); (2) Analysis of the result of ArrayList traverse mode 1234567891011121314compare loop performance of ArrayList-----------------------------------------------------------------------List Size | 10,000 | 100,000 | 1,000,000 | 10,000,000-----------------------------------------------------------------------for each | 1 ms | 3 MS | Ms | Ms-----------------------------------------------------------------------for Iterator | 0 ms | 1 ms | Ms | Ms-----------------------------------------------------------------------for List.size () | 1 ms | 1 ms | Ms | Ms-----------------------------------------------------------------------for size = List.size () | 0 ms | 0 ms | 6 ms | Ms-----------------------------------------------------------------------for j--| 0 ms | 1 ms | 6 ms | Ms-----------------------------------------------------------------------PS: Because the first traversal of the list takes a bit more time, for Each result is slightly biased, and several of the type order switches in the test code are found to be time-consuming and for-iterator close. From the above we can see: A. In ARBefore the raylist size is 100,000, the five traversal modes consume almost the same amount of B. After 100,000, the fourth to fifth traversal is faster than the first three, the Get method is better than the iterator mode, and java1234int size = List.size (); for (int j = 0; J < size; J + +) {List.get (j);} The temporary variable size replaces list.size () for better performance. Let's look at the implementation of the ArrayList iterator iterator and get methods Java1234567891011121314151617181920212223242526272829private class Itr Implements Iterator {int cursor;//index of next element to ReturnInt Lastret =-1;//index of the last element returned;-1 if no suchint exp Ectedmodcount = 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);} It can be seen that the next function of get and iterator also obtains elements by directly locating the data, just a few more judgments. C. From the above can be seen even in tens of thousands of ArrayList, a few of the Traverse Way is only about 50ms, and in the commonly used about 100,000 of the time is almost equal, consider the advantages of foreach, we can choose to use a foreach simple way to traverse. (3) Analysis of the result of LinkedList traverse mode 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 | Ms | 7972 ms-----------------------------------------------------------------------for size = List.size () | 0 ms | 0 ms | Ms | 8216 ms-----------------------------------------------------------------------for j--| 0 ms | 1 ms | Ms | 8277 Ms-----------------------------------------------------------------------PS: Because the first traversal of the list takes a bit more time, for Each result is slightly biased, and several of the type order switches in the test code are found to be time-consuming and for-iterator close. From the above we can see: A in the LinkedList size close to 10,000, get mode and iterator way is already poor nearly two orders of magnitude, 100,000 when iterator mode performance is far better than get mode. Let's look at the implementation of iterators and get methods in LinkedList Java123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495 05152private 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;} publi C Boolean Hasnext () {return nextindex < size;} public E Next () {checkforcomodification (); if (!hasnext ()) throw new Nosuc Helementexception (); 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 Speci fied 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;}} As you can see from the above code, the next function of the LinkedList iterator simply gets the next element quickly and returns with the next pointer. The Get method will traverse from the beginning until index subscript, find an element time complexity of O (n), the time of the traversal of the complexity reached O (N2). Therefore, for linkedlist traversal, it is recommended to use foreach to avoid traversal using get. (4) Comparison and analysis of ArrayList and LinkedList traversal mode results from the above order of magnitude, the same is the Foreach Loop traversal, ArrayList and LinkedList time is similar, you can change this example to increase the list Size will find that the two are basically at an order of magnitude. However, the ArrayList get function is directly positioned to get the time complexity of O (1), while the LinkedList get function time complexity is O (n). Combined with space consumption, it is recommended that ArrayList be preferred. For an individual insert delete very much can be used LinkedList. 4, conclusion through the above analysis we can summarize the following: (1) whether ArrayList or LinkedList, traversal recommends using foreach, especially when the amount of data is large linkedlist avoid using get traversal. (2) List use preferred ArrayList. For an individual insert delete very much can be used LinkedList. (3) It is possible to use a subscript in the traversal of the list loop, which is combined with the use of foreach and self-increment count or get mode. Turn from: http://www.trinea.cn/android/arraylist-linkedlist-loop-performance/

ArrayList and linkedlist several kinds of cyclic traversal mode and performance comparison analysis ( Go)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.