In the following piece of code:
if (map.containsKey(key)) {
map.remove(key);
}
Looking at performance, is it useful to first do a Map.containsKey()
check before trying to remove the value from the map?
Same question goes for retrieving values, is it useful to first do the contains check if you know that the map contains no null
values?
if (map.containsKey(key)) {
Object value = map.get(key);
}
remove
returns null
if there's no mapping for key
no exception will be thrown:
public V remove(Object key)
I don't see any reason to perform that if
before trying to remove a key
, perhaps maybe if you want to count how many items where removed from the map..
In the second example, you'll get null
if the key
doesn't exist. Whether to check or not, depends on your logic.
Try not to waste your time on thinking about performance, containsKey
has O(1) time complexity:
This implementation provides constant-time performance for the basic operations (
get
andput
)
is it useful to first do a Map.containsKey() check before trying to remove the value from the map?
No, it is counterproductive:
If you want to remove the item unconditionally, simply call map.remove(key)
.
Same question goes for retrieving values
Same logic applies here. Of course you need to check the result for null
, so in this case if
stays there.
Note that this cleanup exercise is about readability first, and only then about performance. Accessing a map is a fast operation, so accessing it twice is unlikely to cause major performance issues except for some rather extreme cases. However, removing an extra conditional will make your code more readable, which is very important.
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