Java USES ArrayList traversal and efficiency comparison example analysis

  • 2020-04-01 04:05:19
  • OfStack

This article illustrates Java's use of ArrayList traversal and efficiency comparisons. Share with you for your reference. The details are as follows:


ArrayList arrL = new ArrayList();
ArrayList arrLTmp1 = new ArrayList();
ArrayList arrLTmp2 = new ArrayList();
ArrayList arrLTmp3 = new ArrayList();
ArrayList arrLTmp4 = new ArrayList();
for (int i=0;i<1000000;i++){
  arrL.add(" The first "+i+" a ");
}
long t1 = System.nanoTime();
//Method 1
Iterator it = arrL.iterator();
while(it.hasNext()){
  arrLTmp1.add(it.next());
}
long t2 = System.nanoTime();
//Method 2
for(Iterator it2 = arrL.iterator();it2.hasNext();){
  arrLTmp2.add(it2.next());
}
long t3 = System.nanoTime();
//Methods 3
for (String vv :arrL){
  arrLTmp3.add(vv);
}
long t4 = System.nanoTime();
//Methods 4
for(int i=0;i
  arrLTmp4.add(arrL.get(i));
}
long t5 = System.nanoTime();
System.out.println(" The first method is time-consuming: " + (t2-t1)/1000 + " microseconds ");
System.out.println(" The second method is time-consuming: " + (t3-t2)/1000 + " microseconds ");
System.out.println(" The third method is time-consuming: " + (t4-t3)/1000 + " microseconds ");
System.out.println(" The fourth method is time-consuming: " + (t5-t4)/1000 + " microseconds ");

Output results:


 The first method is time-consuming: 143069 microseconds 
 The second method is time-consuming: 381666 microseconds 
 The third method is time-consuming: 125909 microseconds 
 The fourth method is time-consuming: 63693 microseconds 

Change the above 1000000 to 10, and the output is:


 The first method is time-consuming: 307 microseconds 
 The second method is time-consuming: 14 microseconds 
 The third method is time-consuming: 14 microseconds 
 The fourth method is time-consuming: 14 microseconds 

I hope this article has been helpful to your Java programming.


Related articles: