性能 ConcurrentHashmap 与 HashMap [英] Performance ConcurrentHashmap vs HashMap
问题描述
ConcurrentHashMap 的性能与 HashMap 相比如何,尤其是 .get() 操作(我特别感兴趣的是只有少数项目的情况,范围在 0-5000 之间)?
有什么理由不使用 ConcurrentHashMap 而不是 HashMap 吗?
(我知道不允许空值)
更新
澄清一下,显然实际并发访问的情况下性能会受到影响,但是没有并发访问的情况下性能如何比较?
我真的很惊讶地发现这个话题如此古老,而且还没有人提供任何关于这个案例的测试.使用 ScalaMeter
我已经为 HashMap
创建了 add
、get
和 remove
测试和 ConcurrentHashMap
两种场景:
- 使用单线程
- 使用尽可能多的线程,因为我有可用的内核.请注意,因为
HashMap
不是线程安全的,我只是为每个线程创建了单独的HashMap
,但使用了一个共享的ConcurrentHashMap
.
代码可在
总结
如果您想尽快对数据进行操作,请使用所有可用线程.这似乎很明显,每个线程都有 1/n 的全部工作要做.
如果你选择单线程访问使用
HashMap
,它只是更快.对于add
方法,它的效率甚至提高了 3 倍.在ConcurrentHashMap
上只有get
更快,但不多.当在多个线程上操作
ConcurrentHashMap
时,对于每个线程在单独的HashMap
上操作同样有效.因此无需将您的数据划分为不同的结构.
综上所述,ConcurrentHashMap
使用单线程时性能较差,但添加更多线程来完成工作肯定会加快进程.
测试平台
AMD FX6100,16GB 内存
Xubuntu 16.04,Oracle JDK 8 更新 91,Scala 2.11.8
How is the performance of ConcurrentHashMap compared to HashMap, especially .get() operation (I'm especially interested for the case of only few items, in the range between maybe 0-5000)?
Is there any reason not to use ConcurrentHashMap instead of HashMap?
(I know that null values aren't allowed)
Update
just to clarify, obviously the performance in case of actual concurrent access will suffer, but how compares the performance in case of no concurrent access?
I was really surprised to find this topic to be so old and yet no one has yet provided any tests regarding the case. Using ScalaMeter
I have created tests of add
, get
and remove
for both HashMap
and ConcurrentHashMap
in two scenarios:
- using single thread
- using as many threads as I have cores available. Note that because
HashMap
is not thread-safe, I simply created separateHashMap
for each thread, but used one, sharedConcurrentHashMap
.
Code is available on my repo.
The results are as follows:
- X axis (size) presents number of elements written to the map(s)
- Y axis (value) presents time in milliseconds
The summary
If you want to operate on your data as fast as possible, use all the threads available. That seems obvious, each thread has 1/nth of the full work to do.
If you choose a single thread access use
HashMap
, it is simply faster. Foradd
method it is even as much as 3x more efficient. Onlyget
is faster onConcurrentHashMap
, but not much.When operating on
ConcurrentHashMap
with many threads it is similarly effective to operating on separateHashMaps
for each thread. So there is no need to partition your data in different structures.
To sum up, the performance for ConcurrentHashMap
is worse when you use with single thread, but adding more threads to do the work will definitely speed-up the process.
Testing platform
AMD FX6100, 16GB Ram
Xubuntu 16.04, Oracle JDK 8 update 91, Scala 2.11.8
这篇关于性能 ConcurrentHashmap 与 HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!