Quickest implementation of Java Map for a small number of entries

前端 未结 3 1717
遇见更好的自我
遇见更好的自我 2021-02-13 13:15

What is the quickest implementation of java.util.Map for a very small number of entries (under 15 elements or so)? Both thread-safe and non-thread-safe.

3条回答
  •  孤街浪徒
    2021-02-13 13:43

    If you want a compact Map you can use the

    Map map = Collections.synchronizedMap(new HashMap<>());

    if you don't need thread safety, drop the Collections.synchronizedMap And if you want the collection to use as little memory as possible you can do something like this.

    Map map = new HashMap<>(4, 1.0f);

    This will store 4 key/values (or more) using a minimum of memory. It will be about half the size of an empty standard HashMap.

    The problem with using ConcurrentHashMap is that it is heavy weight for a small collection i.e. it uses many objects and about 1 KB of memory if empty.

    To get accurate memory usage, you need to use -XX-UseTLAB on the command line

    public static void main(String sdf[]) throws Exception {
        testCreateSize("ConcurrentHashMap", ConcurrentHashMap::new);
        testCreateSize("HashMap", HashMap::new);
        testCreateSize("synchronized HashMap", () -> {
            return Collections.synchronizedMap(new HashMap<>());
        });
        testCreateSize("small synchronized HashMap", () -> {
            return Collections.synchronizedMap(new HashMap<>(4, 2.f));
        });
    
    }
    
    public static void testCreateSize(String description, Supplier> supplier) {
        // warmup.
        supplier.get();
        long start = memoryUsed();
        Map map = supplier.get();
        for (int i = 0; i < 4; i++) {
            map.put(i, i);
        }
        long used = memoryUsed() - start;
        System.out.printf("Memory used for %s, was %,d bytes%n", description, used);
    
    }
    
    public static long memoryUsed() {
        return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    }
    

    prints

    Memory used for ConcurrentHashMap, was 272 bytes
    Memory used for HashMap, was 256 bytes
    Memory used for synchronized HashMap, was 288 bytes
    Memory used for small synchronized HashMap, was 240 bytes
    

    You can save 32 more bytes by using synchronized methods in the class which uses the map.

提交回复
热议问题