I would like to get to know which method is actually better to use when I need to create array containing many maps with exact same keys in it. I just think about 3 methods here:
- Reinitialize the
new HashMap()
.Map t = new HashMap(); t.put(k, v); list.add(t); t = new HashMap(); t.put(k, v); list.add(t); // ... and so on
- Use
map.clear()
.Map t = new HashMap(); t.put(k, v); list.add(t); t.clear(); t.put(k, v); list.add(t); // ... and so on
- Just
put()
right away.Map t = new HashMap(); t.put(k, v); list.add(t); t.put(k, v); list.add(t); // ... and so on
I have read the articles about the use of new HashMap()
vs map.clear()
here. However, for performance-wise, I still look for "more-optimized" one. Thus, I decided to take a look of put
method of Java Map.
When I take a look at Java doc of Map, I saw that the put()
function is actually check if key exists before place the value. What it actually does is like below:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
Suppose that the data is so so many (just say 10000 maps to be inserted to the list and each map has 100 key-value pairs) What is actually the best practice for the performance:
- Time-wise (Runtime)
- Resource-wise (Memory)
among these three methods while considering the data integrity (expected result is no any mistake for each maps inside the list)?