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.
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
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.