Comparing Java's List, Set, Map query speed

@org.junit.jupiter.api.Test
    public void compareArrayListAndHashMapAndSet1(){
    
    
        Map<Long, Long> map = new HashMap<>();
        for (int i = 0; i < 1000_0000; i++) {
    
    
            map.put(i+1L, i+1L);
        }
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000_0000; i++) {
    
    
            boolean b = map.containsKey(i + 1L);
        }
        long end = System.currentTimeMillis();
        System.out.println("1000w元素 map耗时:" + (end-start));

        List<Long> list = new ArrayList<>();
        for (int i = 0; i < 10_0000; i++) {
    
    
            list.add(i+1L);
        }
        long start2 = System.currentTimeMillis();
        for (int i = 0; i < 10_0000; i++) {
    
    
            boolean b = list.contains(i + 1L);
        }
        long end2 = System.currentTimeMillis();
        System.out.println("10W元素 list耗时:" + (end2-start2));

        Set<Long> set = new HashSet<>();
        for (int i = 0; i < 1000_0000; i++) {
    
    
            set.add(i+1L);
        }
        long start3 = System.currentTimeMillis();
        for (int i = 0; i < 1000_0000; i++) {
    
    
            boolean b = set.contains(i + 1L);
        }
        long end3 = System.currentTimeMillis();
        System.out.println("1000w元素 set耗时:" + (end3-start3));

    }

Insert picture description here

in conclusion:

The difference between map and set is not big
because of the hash table used in the bottom layer; because I only store a Long type id,
the list speed when I choose Set 1000w elements is too slow, goodbye!
Recommend key, value to choose HashMap;

I found a picture online:

Insert picture description here
Connect here: (Respect the original)
https://blog.csdn.net/high2011/article/details/106742629

Guess you like

Origin blog.csdn.net/weixin_42096620/article/details/111310627