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