Comparison of the efficiency of iterator and enhanced for loops in Java

Source: Internet
Author: User

This problem was recently encountered in optimizing the code: What is the efficiency of the iterator and the enhanced for loop? Before learning, it seems to remember that the teacher said to traverse the collection (such as list), the use of iterator seems normal, because it is dedicated, but the efficiency of the operation is not really considered, today did an experiment: a simple comparison of the two, concluded that: Enhanced for loop runs more efficiently. But I am not sure whether this will represent the whole situation, here just record, make a reference, later there is a new understanding to add, welcome everyone to criticize correct.

1      Public Static voidMain (string[] args) {2 test ();3     }4     5      Public Static voidTest () {6         7list<integer> list =NewArraylist<integer>();8         intFlag = 100000;9         intI=0;Ten          while(i<flag) { One List.add (i); Ai++; -         } -          the         //iterator Test -         LongStart =System.currenttimemillis (); -Iterator<integer> Iterator =list.iterator (); -              while(Iterator.hasnext ()) { + System.out.print (Iterator.next ()); -             } +         LongEnd =System.currenttimemillis (); ASystem.out.println ("Iterator this execution consumes" + (End-start) + "milliseconds"); at          -         //Enhanced for loop testing -         LongStart2 =System.currenttimemillis (); -              for(Integer inte:list) { - System.out.print (inte); -             } in         LongEnd2 =System.currenttimemillis (); -System.out.println ("For this execution consumes" + (END2-START2) + "milliseconds"); to}

The result of the operation is:

Comparison of the efficiency of iterator and enhanced for loops in Java

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.