Package com.cn;
Import Java.util.HashMap;
Import Java.util.Iterator;
Import Java.util.Map.Entry; public class Maptest {public static void main (string[] args) {hashmap<integer, string> map = new Hashmap<inte
GER, string> ();
for (int i=0; i<40000; i++) {map.put (i, "first" +i+ ")";
}//Cycle the first long T1 = System.nanotime ();
Object key[] = Map.keyset (). ToArray ();
for (int i=0; i<map.size (); i++) {map.get (key[i));
Long t2 = System.nanotime ();
Loop the second for (Entry<integer, string> entry:map.entrySet ()) {entry.getvalue ();
long t3 = System.nanotime ();
Loop the third kind of iterator<integer> it = Map.keyset (). iterator ();
while (It.hasnext ()) {Integer II = (integer) it.next ();
Map.get (ii);
long T4 = System.nanotime ();
Loop fourth for (Integer Kk:map.keySet ()) {map.get (KK);
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 is time-consuming: 101918 microseconds
The second method is time-consuming: 49042 microseconds
The third method is time-consuming: 82706 microseconds
The fourth method is time-consuming: 75093 microseconds
to change the above 1000000 to 10, the output is as follows:
The first method is time-consuming: 806 microseconds
The second method is time-consuming: 453 microseconds
The third method is time-consuming: 19 microseconds
The fourth method is time-consuming: 17 microseconds
Change to:
The first method is time-consuming: 909 microseconds
The second method is time-consuming: 631 microseconds
The third method is time-consuming: 154 microseconds
The fourth method is time-consuming: 141 microseconds
After testing, the third and fourth methods are almost as time-consuming, and the second method is more efficient when the data is tens of thousands.