LoginSignup
1
2

More than 5 years have passed since last update.

HashMapから値を取出すときの速度について

Posted at

速度について確認してみた

参考:https://qiita.com/kei2100/items/0ce97733c92fdcb9c5a9

HashMapから値をValueを取出す時に、これまでkeySet()を使ていたのですが、entrySet()を用いた方が速度が速いとの事なので確認してみました。

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<>();

        //Mapの作成
        for(int i=0; i<1000; i++){
            map.put(i,i);
        }

        //二通りで出力してみる
        //keySet()を用いる方法
        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()を用いる方法
        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");
    }
}

1000個のHashMapを代入するのにkeySet()を用いる方法とentrySet()を用いる方法では、私のPCだと、だいたいentrySet()を用いた方が1msほど早くなりました。
標準出力をしたりするとその差は広がりました。

難点としては、読みづらいことでしょうか。
今後こちらの方法でも書けるようにメモしておきます。

1
2
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2