A case study of Java using ArrayList traversal and efficiency comparison _java

Source: Internet
Author: User

This article describes the Java use of ArrayList traversal and efficiency comparisons. Share to everyone for your reference. Specifically 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 ("+i+");
}
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 ();
Method 3 for
(String vv:arrl) {
  arrltmp3.add (vv);
}
long T4 = System.nanotime ();
Method 4 for
(int i=0;i
  arrltmp4.add (Arrl.get (i));
}
Long T5 = System.nanotime ();
System.out.println ("First method time consuming:" + (T2-T1)/1000 + "microsecond");
System.out.println ("second method time consuming:" + (T3-T2)/1000 + "microsecond");
System.out.println ("Third method time consuming:" + (T4-T3)/1000 + "microsecond");
System.out.println ("Fourth method time consuming:" + (T5-T4)/1000 + "microsecond");

Output results:

The first method takes time: 143069 microseconds the
second method takes time: 381666 microseconds the
third method takes time: 125909 microseconds the
fourth method takes time: 63693 microseconds

Change the above 1000000 to 10 and the output is:

The first method takes time: 307 microseconds The
second method takes time: 14 microseconds the
third method takes time: 14 microseconds The
fourth method takes time: 14 microseconds

I hope this article will help you with your Java programming.

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.