Many articles compare these approaches and all are in favor of entrySet over keySet. All of them take into account the speed, but none heap usage.
- https://coderanch.com/t/203203/java/entrySet-keySet-Map
- https://howtodoinjava.com/java/collections/hashmap/performance-comparison-of-different-ways-to-iterate-over-hashmap/
Recently, I have implemented some code using ConcurrentHashMap and the map on average held 200K - 300K items. We iterate through the whole map every 30s.
During the performance test of the software, I found that GC was taking a hit every 30s, causing lots of objects to be allocated (and freed subsequently). Going further into the analysis, I have found that an abnormal amount of Entry<K, V> objects were allocated every 30s.
After switching to iterating over keySet, no allocation spikes showed.
I know that:
for (String key : testMap.keySet()) {
testMap.get(key);
}
raises warning in both any half-decent IDEs and SonarQube. The performance does also vary with the implementation of the map (e.g. in TreeMap). But it sort of does a better job than the entrySet.
Some other SO answers also point out that the cost of doing O(1) lookup (and hashCode) is far greater than allocating a new Entry each and every time
So, what is your take on this?