A comparison of the speed between keyset and EntrySet in traversing HashMap __java

Source: Internet
Author: User

Today on the Internet to see a traversal hashmap to value, with keyset efficiency than with entryset low, and then tested again, found that in fact can not generalize

The following code is executed multiple times, with different values

According to the online example, Hm.put (i, "Thans");

EntrySet: Elapsed Time MS: 16
Keyset: Elapsed time MS: 31

EntrySet: Elapsed Time MS: 47
Keyset: Elapsed Time MS: 15

public void Testhashmap () {
HashMap hm= new HashMap ();
for (int i=0;i<1000;i++) {
Hm.put (i, "abc");

System.out.println ("EntrySet:");
Long bs = Calendar.getinstance (). Gettimeinmillis ();
Iterator it = Hm.entryset (). iterator ();

while (It.hasnext ()) {
Entry Entry = (Entry) it.next ();
System.out.print (Entry.getkey () + "[" +entry.getvalue () + "]");
System.out.print ("[" +entry.getvalue () + "]");
System.out.println ();
System.out.println ("Elapsed time milliseconds:");
System.out.println (Calendar.getinstance (). Gettimeinmillis ()-bs);
System.out.println ("Take key=0:" +hm.get (0). toString ());
System.out.println ("keyset:");

Long BS2 = Calendar.getinstance (). Gettimeinmillis ();
Iterator it2 = Hm.keyset (). iterator ();
while (It2.hasnext ()) {
Integer KS = (integer) it2.next ();
System.out.print ("[" +hm.get (KS) + "]");
System.out.println ();
System.out.println ("Elapsed time milliseconds:");
System.out.println (Calendar.getinstance (). Gettimeinmillis ()-BS2);

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.