对于非常少量的条目(小于15个),最快的 java.util.Map 实现是什么?同时支持线程安全和非线程安全。
public static void main(String[] args) {
System.out.println("\n===== ConcurrentHashMap =====");
testMap(new ConcurrentHashMap<>());
System.out.println("\n===== Collections.synchronizedMap() =====");
testMap(Collections.synchronizedMap(new HashMap<>()));
}
static final int N = 5;
static final int R = 1000000;
public static void testMap(Map map) {
long startTime = System.nanoTime();
System.out.println("\n-- " + N*R + " puts(key, value) --");
startTime = System.nanoTime();
for (int j = 0; j < R; j++) {
for (int i = 0; i < N; i++)
map.put(i, new float[] { 0f, 1f, 2f, 3f, 4f });
map.clear();
}
System.out.println((System.nanoTime() - startTime) / 1000000000.0);
System.out.println("\n-- " + N*R + " get(key) --");
startTime = System.nanoTime();
for (int j = 0; j < R; j++) {
for (int i = 0; i < N; i++)
map.get(i);
map.clear();
}
System.out.println((System.nanoTime() - startTime) / 1000000000.0);
}
}
我的测试结果如下:
===== ConcurrentHashMap =====
5000000 次 puts(key, value) - 0.99714195 秒
5000000 次 get(key) - 0.452227427 秒
===== Collections.synchronizedMap() =====
5000000 次 puts(key, value) - 0.586431367 秒
5000000 次 get(key) - 0.376051088 秒
所以,Peter 可能是正确的 - 对于小型的映射表,Collections.synchronizedMap()
更快。
Collections.synchronizedMap
。如果你希望集合使用最少的内存,可以像这样做:-XX-UseTLAB
。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<Map<Integer, Integer>> supplier) {
// warmup.
supplier.get();
long start = memoryUsed();
Map<Integer, Integer> 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();
}
打印
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
如果在使用地图的类中使用同步方法,可以节省32个字节。
HashMap<String, Object> map = new HashMap <String, Object> ();
这将为您提供一个非常简单的映射,其键类型为String,值类型为Object。
编辑:这是一个非线程安全的版本。
您可以查看ConcurrentHashMaps以获取线程安全映射。
ConcurrentHashMap
实现线程安全。 - BrajMap<Integer, String>
,还是一个Map<Double, Long>
等等? - arshajii