[JAVA] About the speed when fetching values from HashMap

I checked the speed

Reference: https://qiita.com/kei2100/items/0ce97733c92fdcb9c5a9

I used to use keySet () when fetching a value from HashMap, but I heard that using entrySet () is faster, so I checked it.

java


import java.util.HashMap;
import java.util.Map.Entry;

public class HashmapentrySetAndkeySet {
	public static void main(String[] args) {

		HashMap<Integer,Integer> map = new HashMap<>();

		//Creating a map
		for(int i=0; i<1000; i++){
			map.put(i,i);
		}

		//Try to output in two ways
		//keySet()Method using
		long start1 = System.currentTimeMillis();
		for(Integer key : map.keySet()){
			Integer value = map.get(key);
			//System.out.println(value);
		}
		long end1 = System.currentTimeMillis();
		System.out.println((end1-start1)+"ms");

		//entrySet()Method using
		long start2 = System.currentTimeMillis();
		for(Entry<Integer, Integer> entry : map.entrySet()){
			Integer value = entry.getValue();
			//System.out.println(value);
		}
		long end2 = System.currentTimeMillis();
		System.out.println((end2-start2)+"ms");
	}
}

In the method of using keySet () and the method of using entrySet () to assign 1000 HashMaps, it is about 1ms faster to use entrySet () on my PC. The difference widened when standard output was used.

The difficulty is that it's hard to read. Make a note so that you can write it using this method in the future.

Recommended Posts

About the speed when fetching values from HashMap
[Android] Get random keys and values from HashMap
[CentOS 8] About the work when rebuilding ConoHa VPS
About the mechanism when displaying the GUI with Docker
About the method
About numerical values
About the package
About the usefulness of monads from an object-oriented perspective
About Class loading and initialization when the JVM starts
[Note] When the page access speed does not increase
Talk about going through the source path when delombok