Objective
Through this article you can understand the list of five traversal methods and their respective performance and the implementation of foreach and iterator, deepen the understanding of ArrayList and LinkedList implementation. Let's take a look below.
Five ways to traverse a list
1, for Each loop
list<integer> list = new arraylist<integer> ();
for (Integer j:list) {
//use J
}
2. Display Call Collection iterator
list<integer> list = new arraylist<integer> ();
for (iterator<integer> iterator = List.iterator (); Iterator.hasnext ();) {
iterator.next ();
}
Or
list<integer> list = new arraylist<integer> ();
Iterator<integer> iterator = List.iterator ();
while (Iterator.hasnext ()) {
iterator.next ();
}
3, subscript increment cycle, the termination condition for each call size () function comparison judgment
list<integer> list = new arraylist<integer> ();
for (int j = 0; J < List.size (); j + +) {
list.get (j);
}
4, subscript increment cycle, the termination condition is equal to size () The temporary variable comparison judgment
list<integer> list = new arraylist<integer> ();
int size = List.size ();
for (int j = 0; J < size; J +) {
list.get (j);
}
5, Subscript descending cycle
list<integer> list = new arraylist<integer> ();
for (int j = list.size ()-1; J >= 0; j--) {
list.get (j);
}
Performance test and comparison of list five traversal modes
The following is a performance test code that outputs the amount of time spent ArrayList and linkedlist various traversal modes for different order of magnitude.
Package cn.trinea.java.test;
Import Java.text.DecimalFormat;
Import java.util.ArrayList;
Import Java.util.Calendar;
Import Java.util.Iterator;
Import java.util.LinkedList;
Import java.util.List; /** * javalooptest * * @author www.trinea.cn 2013-10-28/public class Javalooptest {public static void main (Strin
G[] args) {System.out.print ("Compare loop performance of ArrayList");
Looplistcompare (Getarraylists (10000, 100000, 1000000, 9000000));
System.out.print ("\r\n\r\ncompare Loop performance of LinkedList");
Looplistcompare (getlinkedlists (100, 1000, 10000, 100000)); public static list<integer>[] getarraylists (int ... sizearray) {list<integer>[] Listarray = new ArrayList
[Sizearray.length];
for (int i = 0; i < listarray.length i++) {int size = Sizearray[i];
list<integer> list = new arraylist<integer> ();
for (int j = 0; J < size; J +) {List.add (j);
} Listarray[i] = list;
return listarray; } public static LIst<integer>[] getlinkedlists (int ... sizearray) {list<integer>[] Listarray = new linkedlist[
Sizearray.length];
for (int i = 0; i < listarray.length i++) {int size = Sizearray[i];
list<integer> list = new linkedlist<integer> ();
for (int j = 0; J < size; J +) {List.add (j);
} Listarray[i] = list;
return listarray;
public static void Looplistcompare (LIST<INTEGER>. Listarray) {printheader (Listarray);
Long StartTime, Endtime;
Type 1 for (int i = 0; i < listarray.length i++) {list<integer> List = listarray[i];
StartTime = Calendar.getinstance (). Gettimeinmillis ();
for (Integer j:list) {//Use J} endtime = Calendar.getinstance (). Gettimeinmillis ();
Printcosttime (i, Listarray.length, "for each", endtime-starttime);
}//Type 2 for (int i = 0; i < listarray.length i++) {list<integer> List = listarray[i]; StartTime = Calendar.getinstance (). GettimeinmilLis ();
Iterator<integer> iterator = List.iterator ();
while (Iterator.hasnext ()) {//Iterator.next (); for (iterator<integer> iterator = List.iterator (); Iterator.hasnext ();)
{Iterator.next ();
} Endtime = Calendar.getinstance (). Gettimeinmillis ();
Printcosttime (i, Listarray.length, "for iterator", endtime-starttime);
}//Type 3 for (int i = 0; i < listarray.length i++) {list<integer> List = listarray[i];
StartTime = Calendar.getinstance (). Gettimeinmillis ();
for (int j = 0; J < List.size (); j + +) {List.get (j);
} Endtime = Calendar.getinstance (). Gettimeinmillis ();
Printcosttime (i, Listarray.length, "for List.size ()", endtime-starttime);
}//Type 4 for (int i = 0; i < listarray.length i++) {list<integer> List = listarray[i];
StartTime = Calendar.getinstance (). Gettimeinmillis ();
int size = List.size ();
for (int j = 0; J < size; J +) {List.get (j); } EndTime = Calendar.getinstance (). Gettimeinmillis ();
Printcosttime (i, Listarray.length, "for size = List.size ()", endtime-starttime);
}//Type 5 for (int i = 0; i < listarray.length i++) {list<integer> List = listarray[i];
StartTime = Calendar.getinstance (). Gettimeinmillis ();
for (int j = list.size ()-1; J >= 0; j--) {list.get (j);
} Endtime = Calendar.getinstance (). Gettimeinmillis ();
Printcosttime (i, Listarray.length, "for j--", endtime-starttime);
} static int first_column_length = Other_column_length = Total_column_length = 71;
Static final DecimalFormat Comma_format = new DecimalFormat ("#,###");
public static void Printheader (LIST<INTEGER>. Listarray) {printrowdivider (); for (int i = 0; i < listarray.length i++) {if (i = = 0) {StringBuilder sb = new StringBuilder (). Append ("list s
Ize ");
while (Sb.length () < First_column_length) {sb.append ("");
} System.out.print (SB); StringBuilder sb = new StringBuilder (). Append ("|").
Append (Comma_format.format (Listarray[i].size ()));
while (Sb.length () < Other_column_length) {sb.append ("");
} System.out.print (SB);
} total_column_length = First_column_length + other_column_length * listarray.length;
Printrowdivider ();
public static void Printrowdivider () {System.out.println ();
StringBuilder sb = new StringBuilder ();
while (Sb.length () < Total_column_length) {sb.append ("-");
} System.out.println (SB); public static void Printcosttime (int i, int size, String casename, long costtime) {if (i = = 0) {StringBuilder SB
= new StringBuilder (). append (Casename);
while (Sb.length () < First_column_length) {sb.append ("");
} System.out.print (SB); StringBuilder sb = new StringBuilder (). Append ("|").
Append (Costtime). Append ("MS");
while (Sb.length () < Other_column_length) {sb.append ("");
} System.out.print (SB);
if (i = = size-1) { Printrowdivider (); }
}
}
PS: If you run the report exception in thread “main” java.lang.OutOfMemoryError: Java heap space
, please main
reduce the list size
size of the function inside.
Where the getArrayLists
function returns a different size
ArrayList, the getLinkedLists
function returns a different size
LinkedList.
loopListCompare
The function uses the above traversal mode 1-5 to traverse the list in each list array (including the different size list).
print
The beginning function is an output auxiliary function.
Test environment for WINDOWS7 32-bit system 3.2G dual-core CPU 4G memory, Java 7,eclipse-xms512m-xmx512m
The final test results are as follows:
Compare loop performance of ArrayList-----------------------------------------------------------------------list Size | 10,000 | 100,000 | 1,000,000 | 10,000,000-----------------------------------------------------------------------for each | 1 ms | 3 MS | Ms | 152 Ms-----------------------------------------------------------------------for iterator | 0 ms | 1 ms | Ms | 114 Ms-----------------------------------------------------------------------for List.size () | 1 ms | 1 ms | Ms | 128 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 Suit | 7972 ms-----------------------------------------------------------------------for size = List.size () | 0 ms | 0 ms | Mobile Suit | 8216 ms-----------------------------------------------------------------------for j--| 0 ms | 1 ms | Mobile Suit | 8277 Ms-----------------------------------------------------------------------
The first table is the ArrayList contrast result, the second table is the LinkedList contrast result.
The table is horizontal for the same traversal of different size list traversal time consumption, portrait of the same list of different traversal methods of time spent.
PS: because the first traversal of the list will be a little more time-consuming, for each
the result is slightly biased, the test code in a few of the type sequence will be found, for each
time-consuming and for iterator
close.
Performance test results Analysis of traversal mode
1, foreach Introduction
foreach is a powerful cyclic structure introduced by the Java SE5.0 and for (Integer j : list)
should be read for each int in list
.
for (Integer j : list)
Implementation is almost equivalent to
Iterator<integer> iterator = List.iterator ();
while (Iterator.hasnext ()) {
Integer j = iterator.next ();
}
The foreach code is simple to write, does not have to care about subscript initial value and termination value and bounds, so it is not easy to make mistakes
2, ArrayList traversal mode results analysis
A. Before the ArrayList size is 100,000, the five traversal modes have almost the same time consuming
B. After 100,000, the fourth to fifth traversal method is faster than the first three, the get way is superior to the iterator mode, and
int size = List.size ();
for (int j = 0; J < size; J +) {
list.get (j);
}
Substitute the temporary variable size for list.size()
better performance. Let's look at Iterator
get
the implementation of iterators and methods in ArrayList
Private class Itr implements iterator<e> {
int cursor; Index of next element to return
int lastret =-1;//index of the last element returned-1 if no such
int expected Modcount = 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
the functions that can be seen and used Iterator
in the next
same way are directly locating the data to get elements, just a few more judgments.
C. From the above can be seen even in tens of millions of ArrayList, several traversal methods are not about 50ms, and in the commonly used 100,000 or so time almost equal, considering the merits of foreach, we can choose a simple way to traverse.
3, LinkedList traversal mode results analysis
A. When the size of the LinkedList is close to 10,000, the get
way and Iterator
mode have been nearly two orders of magnitude, and 100,000-time Iterator
performance is far better than the get mode.
Let's look at get
the implementation of iterators and methods in LinkedList
Private class Listitr implements listiterator<e> {private node<e> lastreturned = null;
Private node<e> 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<e> Node (int index) {//Assert Iselementindex (index);
if (Index < (size >> 1)) {node<e> x = i;
for (int i = 0; i < index; i++) x = X.next;
return x;
else {node<e> x = last; for (int i = Size-1; i > Index;
i--) x = X.prev;
return x; }
}
From the code above, you can see that the function of the LinkedList iterator next
simply gets the next element quickly and returns with the next pointer. The Get method will iterate through the index, looking for an element with a time complexity of O (n), the time complexity of the traversal reached O (N2).
Therefore, it is recommended to use foreach for LinkedList traversal, avoiding the use of the get
way traversal.
4, ArrayList and LinkedList traversal method results Comparison analysis
From the above order of magnitude, the same is the Foreach Loop traversal, ArrayList and LinkedList time is similar, can be slightly modified This example list size
will find that the two are basically in an order of magnitude.
However ArrayList get
, the time complexity of the function direct location acquisition is O (1), while the LinkedList get function time complexity is O (n).
Combined with the space consumption, we recommend the preferred ArrayList. For individual inserts delete very much can use LinkedList.
Conclusion Summary
Through the above analysis we can basically summarize:
- Whether ArrayList or LinkedList, traversal recommends foreach, especially when the volume of data is large linkedlist avoid using get traversal.
- List uses preferred ArrayList. For individual inserts delete very much can use LinkedList.
- You might want to use a subscript within the traversal list loop, considering whether to use foreach and self count or get mode.
Summarize
The above is the entire content of this article, I hope this article content for everyone to learn or use Java time can help, if there is doubt you can message exchange.