original text

1. This paper

about Java in Map Traversal of , Many articles recommend the use of entrySet, I think it's better than that keySet It's a lot more efficient . The reason is that :entrySet The way to get all at once key and value Set ; and keySet All I got was key Set , For each key, All going Map Find one more time in value, This reduces the overall efficiency . So what's the actual situation ?

To understand the real gap in traversal performance , Included in traversal key+value、 Traverse key、 Traverse value And so on , I tried to do some comparative tests .

2. Contrast test

It started with a simple test , But it turns out that keySet Better performance , This makes me very puzzled , Not all say entrySet Obviously better than keySet Do you ? For further verification , So different test data are used for more detailed comparative test .

2.1 Test data

2.1.1 HashMap Test data

  • HashMap-1, The size is 100 ten thousand ,key and value Are all String,key The value of is 1、2、3……1000000:

Map<String, String> map = new HashMap<String, String>();

String key, value;

for (i = 1; i <= num; i++) {

    key = "" + i;

    value = "value";

map.put(key, value);

}

  • HashMap-2, The size is 100 ten thousand ,key and value Are all String,key The value of is 50、100、150、200、……、50000000:

Map<String, String> map = new HashMap<String, String>();

String key, value;

for (i = 1; i <= num; i++) {

    key = "" + (i * 50);

    value = "value";

map.put(key, value);

}

2.1.2 TreeMap Test data

  • TreeMap-1, The size is 100 ten thousand ,key and value Are all String,key The value of is 1、2、3……1000000:

Map<String, String> map = new TreeMap<String, String>();

String key, value;

for (i = 1; i <= num; i++) {

    key = "" + i;

    value = "value";

map.put(key, value);

}

  • TreeMap-2, The size is 100 ten thousand ,key and value Are all String,key The value of is 50、100、150、200、……、50000000, More discrete :

Map<String, String> map = new TreeMap<String, String>();

String key, value;

for (i = 1; i <= num; i++) {

    key = "" + (i * 50);

    value = "value";

map.put(key, value);

}

2.2 Test scenarios

Separate use keySet、entrySet and values Test three scenarios in a variety of ways : Traverse key+value、 Traverse key、 Traverse value Scene .

2.2.1 Traverse key+value

  • keySet Traverse key+value( How to write it 1):

Iterator<String> iter = map.keySet().iterator();

while (iter.hasNext()) {

key = iter.next();

value = map.get(key);

}

  • keySet Traverse key+value( How to write it 2):

for (String key : map.keySet()) {

value = map.get(key);

}

  • entrySet Traverse key+value( How to write it 1):

Iterator<Entry<String, String>> iter = map.entrySet().iterator();

Entry<String, String> entry;

while (iter.hasNext()) {

entry = iter.next();

key = entry.getKey();

value = entry.getValue();

}

  • entrySet Traverse key+value( How to write it 2):

for (Entry<String, String> entry: map.entrySet()) {

key = entry.getKey();

value = entry.getValue();

}

2.2.2 Traverse key

  • keySet Traverse key( How to write it 1):

Iterator<String> iter = map.keySet().iterator();

while (iter.hasNext()) {

key = iter.next();

}

  • keySet Traverse key( How to write it 2):

for (String key : map.keySet()) {

}

  • entrySet Traverse key( How to write it 1):

Iterator<Entry<String, String>> iter = map.entrySet().iterator();

while (iter.hasNext()) {

key = iter.next().getKey();

}

  • entrySet Traverse key( How to write it 2):

for (Entry<String, String> entry: map.entrySet()) {

key = entry.getKey();

}

2.2.3 Traverse value

  • keySet Traverse value( How to write it 1):

Iterator<String> iter = map.keySet().iterator();

while (iter.hasNext()) {

value = map.get(iter.next());

}

  • keySet Traverse value( How to write it 2):

for (String key : map.keySet()) {

value = map.get(key);

}

  • entrySet Traverse value( How to write it 1):

Iterator<Entry<String, String>> iter = map.entrySet().iterator();

while (iter.hasNext()) {

value = iter.next().getValue();

}

  • entrySet Traverse value( How to write it 2):

for (Entry<String, String> entry: map.entrySet()) {

value = entry.getValue();

}

  • values Traverse value( How to write it 1):

Iterator<String> iter = map.values().iterator();

while (iter.hasNext()) {

value = iter.next();

}

  • values Traverse value( How to write it 2):

for (String value : map.values()) {

}

2.3 test result

2.3.1 HashMap test result

Company : millisecond

HashMap-1

HashMap-2

keySet Traverse key+value( How to write it 1)

39

93

keySet Traverse key+value( How to write it 2)

38

87

entrySet Traverse key+value( How to write it 1)

43

86

entrySet Traverse key+value( How to write it 2)

43

85

Company : millisecond

HashMap-1

HashMap-2

keySet Traverse key( How to write it 1)

27

65

keySet Traverse key( How to write it 2)

26

64

entrySet Traverse key( How to write it 1)

35

75

entrySet Traverse key( How to write it 2)

34

74

Company : millisecond

HashMap-1

HashMap-2

keySet Traverse value( How to write it 1)

38

87

keySet Traverse value( How to write it 2)

37

87

entrySet Traverse value( How to write it 1)

34

61

entrySet Traverse value( How to write it 2)

32

62

values Traverse value( How to write it 1)

26

48

values Traverse value( How to write it 2)

26

48

2.3.2 TreeMap test result

Company : millisecond

TreeMap-1

TreeMap-2

keySet Traverse key+value( How to write it 1)

430

451

keySet Traverse key+value( How to write it 2)

429

450

entrySet Traverse key+value( How to write it 1)

77

84

entrySet Traverse key+value( How to write it 2)

70

68

Company : millisecond

TreeMap-1

TreeMap-2

keySet Traverse key( How to write it 1)

50

49

keySet Traverse key( How to write it 2)

49

48

entrySet Traverse key( How to write it 1)

66

64

entrySet Traverse key( How to write it 2)

65

63

Company : millisecond

TreeMap-1

TreeMap-2

keySet Traverse value( How to write it 1)

432

448

keySet Traverse value( How to write it 2)

430

448

entrySet Traverse value( How to write it 1)

62

61

entrySet Traverse value( How to write it 2)

62

61

values Traverse value( How to write it 1)

46

46

values Traverse value( How to write it 2)

45

46

3. Conclusion

3.1 If you use HashMap

  1. At the same time through key and value when ,keySet And entrySet The performance difference of the method depends on key The details of , Such as complexity ( Complex object )、 Dispersion 、 Conflict rate, etc . In other words , Depending on HashMap lookup value The cost of .entrySet Take out all at once key and value There is a performance overhead for the operation of , When the loss is less than HashMap lookup value The cost of ,entrySet The performance advantage will be reflected . For example, in the above comparative test , When key Is the simplest numeric string ,keySet It could be more efficient , Time ratio entrySet Less 10%. Generally speaking, it is recommended to use entrySet. Because when key It's very simple. , Its performance may be slightly lower than keySet, But it's controllable ; And with the key Complication ,entrySet It's going to be obvious . Of course , We can choose according to the actual situation
  2. Just traverse key when ,keySet The method is more suitable , because entrySet Will be useless value It's also taken out , Wasted performance and space . In the above test results ,keySet Than entrySet The method takes less time 23%.
  3. Just traverse value when , Use vlaues Method is the best choice ,entrySet It would be slightly better than keySet Method .
  4. In different ways of traversal , The following is recommended , It's a little more efficient :

for (String key : map.keySet()) {

value = map.get(key);

}

for (Entry<String, String> entry: map.entrySet()) {

key = entry.getKey();

value = entry.getValue();

}

for (String value : map.values()) {

}

3.2 If you use TreeMap

  1. At the same time through key and value when , And HashMap Different ,entrySet Its performance is much higher than keySet. This is from TreeMap The query efficiency of , in other words ,TreeMap lookup value It's expensive , Significantly higher than entrySet Take out all at once key and value The cost of . therefore , Traverse TreeMap It is highly recommended to use entrySet Method .
  2. Just traverse key when ,keySet The method is more suitable , because entrySet Will be useless value It's also taken out , Wasted performance and space . In the above test results ,keySet Than entrySet The method takes less time 24%.
  3. Just traverse value when , Use vlaues Method is the best choice ,entrySet It's obviously better than keySet Method .
  4. In different ways of traversal , The following is recommended , It's a little more efficient :

for (String key : map.keySet()) {

value = map.get(key);

}

for (Entry<String, String> entry: map.entrySet()) {

key = entry.getKey();

value = entry.getValue();

}

for (String value : map.values()) {

}

Java Map Traversal of the choice of more related articles

  1. java map Traversal mode and efficiency

    Reprinted from Java Map The choice of traversal mode . Only the traversal method and conclusion are given . The test data can be read in the original text . If you use HashMap At the same time through key and value when ,keySet And entrySet The performance difference of the method depends on ke ...

  2. java Map Traverse

    http://www.cnblogs.com/fczjuever/archive/2013/04/07/3005997.html 1. This paper about Java in Map Traversal of , Many articles recommend the use of entr ...

  3. java map Traverse 、 Sort , according to value obtain key

    Map Four kinds of traversal : Map<String,String> map = new HashMap<String, String>(); map.put("one" ...

  4. java map Traverse

    from http://rain-2372.iteye.com/blog/1615615 package com.spring.test_B11_aop1; import java.util.HashMap ...

  5. Java LinkList Traverse the way

    1.LinkedList Traversal of a. General for loop ( Random access ) int size = list.size(); for (int i=0; i<size; i++) { list.get( ...

  6. Analyze the wheel ( 8、 ... and )- List.java Various traversal methods and methods of removing elements during traversal

    notes : The game is JDK1.7 edition 1: Try chestnuts first , reanalysis , The code is simple , The notes are clear , You can play by yourself /** * @description: Test how collections traverse and remove elements * @author:godtrue * @crea ...

  7. 2018/1/8 Learning summary ,kettle Brief introduction , Selection and principle of set traversal mode , Background solution to prevent form duplicate submission

    Yesterday, because the current secondary development project is coming to an end , We are required to migrate the data in the production environment database to the new database , But the old database is sqlserver And the new database is ORACLE, It's not just the problem of inconsistent database data type structure , ...

  8. Java HashMap How to traverse

    JDK8 Before , have access to keySet perhaps entrySet To traverse HashMap,JDK8 Introduced in map.foreach Let's do the traversal . keySet It's actually traversal 2 Time , One time, it was turned into Iterator object , Another time is from ...

  9. ( Memo )Java Map Traverse

    // One of the most common traversal methods , The most conventional is the most commonly used , It's not complicated , But it's important. , This is what we are most familiar with , Not much !! public static void work(Map<String, Student> ...

Random recommendation

  1. floyd Algorithm

    Find the shortest distance between two vertices , Intuition is that such problems can be solved by trial and enumeration , It's obviously possible , But we can look at it in a different way , such as , You can describe it this way ,“ In a given set of points ( The number is 1~k,k= The number of all the vertices in the graph ) in ,i ...

  2. 2016 The 11th special session of the weak school alliance 10.5---As Easy As Possible( Multiply )

    Topic link https://acm.bnu.edu.cn/v3/contest_show.php?cid=8506#problem/A problem description As we know, t ...

  3. RobotFrameWork webservice soap The interface test ( Two )

    The last one mentioned doing soap Interface test itself simply wrote a py, Then we simply implement a client that can call the remote interface , Analyze the returned data , But I don't think it's right ,soap The agreement doesn't look like http Agreements are so pervasive , But now a lot of people ...

  4. JavaScript Built-in objects

    Object overview JavaScript It's an object-based script statement , Instead of object-oriented programming languages . The object is the entity of the objective world , It has both properties and methods . The way to access the properties and methods of an object is as follows : Object name . attribute Object name . Method name ...

  5. ExtJs And Ext.core.Element

    <!DOCTYPE html> <html> <head> <title>ExtJs</title> <meta http-equiv ...

  6. JS Generate a random number of a specified length

    /** * Generate... Of specified length UUID * @param len * @param radix * @returns uuid * eg: createUUID(8, 2) "01001010& ...

  7. html-----012--- The change of color

    The color is red . green . A mixture of blue . Color value Color is defined by a hexadecimal symbol , This symbol is made of red . Green and blue values make up (RGB). The minimum value for each color is 0( Hexadecimal :#00). The maximum is 255( Hexadecimal :#FF). ...

  8. Study django Just look at this book !django book 2.0 Chinese version

    Website classification : Download resources > python e-book author : Panda burning incense link :http://www.pythonheidong.com/blog/article/29/ source :python Black hole network dj ...

  9. docker install hadoop

    The last article introduced some of them docker Basic command , This article is to install a HADOOP One . download hadoop Mirror image @~/git/github/docker-ambari (master)$ docker pull ...

  10. php_study progress(1)

    PHP It's a simple grammar . Powerful network programming language . In grammatical form ,PHP Drawing on the popular C.Java and Perl And so on , Very similar to C Language , But more than C The language is simpler , Easy to learn and easy to use , Therefore, it is especially suitable for those who have studied C Language , Yes ...