Performance ConcurrentHashmap vs HashMap
collections, hashmap, java
Solution
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 separate `HashMap` for each thread, but used one, shared `ConcurrentHashMap`.
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. For `add` method it is even as much as 3x more efficient. Only `get` is faster on `ConcurrentHashMap`, but not much.
When operating on `ConcurrentHashMap` with many threads it is similarly effective to operating on separate `HashMaps` 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
Problem
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?