Which one is faster? List.contains() or Map.containsKey()

后端 未结 4 1442
星月不相逢
星月不相逢 2021-01-31 17:34

I\'m writing an algorithm where I look for pairs of values which when added together results in another value I\'m looking for.

I figured out that using a Map

4条回答
  •  攒了一身酷
    2021-01-31 18:15

    HashSet seems to be faster:

    • HashMap: 267
    • ArrayList: 2183
    • HashSet: 57

    Also note that .contains() normally does not need to be called on HashMap and HashSet, but I kept it on the code to more accurately answer your question:

        long t = System.currentTimeMillis();
        HashMap map = new HashMap<>();
        for (int i = 0; i < 10000; i++) {
            String s = (Math.random() * 100) + "";
            if (!map.containsKey(s)) {
                map.put(s, true);
            }
        }
        System.out.println("HashMap: " + (System.currentTimeMillis() - t));
    
        t = System.currentTimeMillis();
        ArrayList list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            String s = (Math.random() * 100) + "";
            if (!list.contains(s)) {
                list.add(s);
            }
        }
        System.out.println("ArrayList: " + (System.currentTimeMillis() - t));
    
        t = System.currentTimeMillis();
        HashSet set = new HashSet<>();
        for (int i = 0; i < 10000; i++) {
            String s = (Math.random() * 100) + "";
            if (!set.contains(s)) {
                set.add(s);
            }
        }
        System.out.println("HashSet: " + (System.currentTimeMillis() - t));
    

提交回复
热议问题