In Java, the faster list traversal speed is than that of ArrayList.

Source: Internet
Author: User

Import java. util. Collections list;
Import java. util. ArrayList;
Import java. util. Random;

Public class TestList {
Private static Random random = new Random ();
Public static void main (String [] args ){
ArrayList <String> arraylist = new ArrayList <String> ();
Shortlist <String> shortlist = new shortlist <String> ();
For (int I = 0; I <50000; I ++ ){
String r = randomString ();
Arraylist. add (r );
Using list. add (r );
}

System. out. println ("arraylist size" + arraylist. size ());
System. out. println ("listing list size" + listing list. size ());
System. out. println ("------");
Long begin = System. currentTimeMillis ();
For (int I = 0; I <1000; I ++ ){
For (int j = 0; j <arraylist. size (); j ++ ){
String s = arraylist. get (j );
}
}
System. out. println ("arraylist get (n) time" + (System. currentTimeMillis ()-begin ));

Begin = System. currentTimeMillis ();
For (int I = 0; I <1000; I ++ ){
For (String s: arraylist ){
}
}
System. out. println ("arraylist foreach time" + (System. currentTimeMillis ()-begin ));

Begin = System. currentTimeMillis ();
For (int I = 0; I <1; I ++)
For (int j = 0; j <partition list. size (); j ++ ){
String s = listing list. get (j );
}
System. out. println ("your list get (n) time" + (System. currentTimeMillis ()-begin) * 1000 );

Begin = System. currentTimeMillis ();
For (int I = 0; I <1000; I ++)
For (String s: Rule List ){
// Configure list. get (j );
}
System. out. println ("your list foreach time" + (System. currentTimeMillis ()-begin ));


}
Protected static String randomString (){
Return Long. toString (random. nextLong (), 36 );
}
}


Arraylist size 50000
Required list size 50000
------
Arraylist get (n) time 562
Arraylists foreach time 1703
Invalid list get (n) time 1922000
Raise list foreach time 813

Conclusion faster list foreach is faster than arraylist foreach.

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.