Performance comparison of the Java list three traversal methods

Source: Internet
Author: User

public static void Compare () {
list<string> list =New Arraylist<string> ();
Set<string> set =New Hashset<string> ();
Forint i=0;i<100000;i++) {
List.add ("A" +i);
}
Long t1=0l,t2=0L;
T1 = System.Currenttimemillis ();
for (String s:list) {
Set.add (s);
}
t2 = System.Currenttimemillis ();
System.Out.println (The time for the foreach traversal is: "+ (T2-T1) +"MM");
Both
T1 = System.Currenttimemillis ();
Forint i=0; I<list.size (); i++) {
String str = list.get (i);
Set.add (List.get (i));
}
t2 = System.Currenttimemillis ();
System.Out.println ( ////three
T1 = System. currenttimemillis ();
Iterator<string> Iterator = List.iterator ();
while (Iterator.hasnext ()) {
String str = Iterator.next ();
Set.add (String) Iterator.next ());
}
t2 = System. Currenttimemillis ();
System. out.println (" iterator traversal time: "+ (T2-T1) +" MM ");
}

foreach traversal is: 45mm
Size traversal time: 14mm
Iterator traversal: 7mm


Java list Three traversal method performance comparison

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.