pat*_*art 11 java collections performance map
对于极少数条目(大约15个元素左右),java.util.Map的最快实现是什么?线程安全和非线程安全.
如果所有条目都可以表示为Enums,请使用EnumMap:
此实现将Map接口的丰富性和安全性与接近数组的速度结合在一起。如果要将枚举映射到值,则应始终使用EnumMap优先于数组。
如果否,则HashMap是一个很好的解决方案。它提供恒定的时间进行基本操作,例如get()和put():
假设哈希函数将元素正确分散在存储桶中,则此实现为基本操作(获取和放置)提供恒定时间的性能。
只需记住capacity在HashMap中设置低值即可:
因此,如果迭代性能很重要,则不要将初始容量设置得过高(或负载因子过低),这一点非常重要。
当然,以上实现不是线程安全的。在这种情况下,最好的线程安全实现是ConcurrentHashMap。它结合了HashMap的高性能和线程安全性。
这是不同Map实现的很好的比较。
编辑:这是不同HashMap实现的有趣比较。看来,至少对于基本类型,有比内置更快的替代方法HashMap。
Edit2:由于Peter Lawrey的回答,我决定进行一些测试,比较ConcurrentHashMap和Collections.synchronizedMap():
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我的结果是:
===== ConcurrentHashMap =====
5000000卖出(关键,价值)-0.99714195秒
5000000 get(密钥)-0.452227427 s
===== Collections.synchronizedMap()=====
5000000卖出(关键,价值)-0.586431367 s
5000000 get(密钥)-0.376051088秒
因此,彼得可能是正确的-对于小地图,Collections.synchronizedMap()速度更快。
| 归档时间: |
|
| 查看次数: |
7426 次 |
| 最近记录: |