In his talk about Effective Java at 54:15 Joshua Bloch recommends to use get
before putIfAbsent
in order to improve performance and concurrency. This leads me to the question why this optimization is already not build in like
public V BETTER_putIfAbsent(K key, V value) {
V result = get(key);
if (result!=null) return result;
return ORIGINAL_putIfAbsent(key, value);
}
I would guess that it is because performance depends on the usage pattern. For a map where most putIfAbsent calls would succeed, then guarding it with a get will be slower. For a map where putIfAbsent will often fail, then guarding it with a get will be faster.
By not making the optimization for the common failure case, you are free to choose which method is faster for your map.
In the example from the video, putIfAbsent will usually fail, so it is faster to guard it with a get.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With