Logan Logan - 3 months ago 6
Java Question

Is it faster to check if a map contains a key or just put that value?

If I know that the value being entered into an entry of the map is the same, would I be better off checking if it's not in the map or just doing the put?
In other words, is

if (!map.containsKey(key)){
map.put(key, value);
}


better than just doing
map.put(key, value)
if I know that the value is the same for the key.

Background:
I am trying to calculate all of the overlaps for a map that maps id to a set of ints. For example: given
{A:1,2,3; B:2,4,6; C:2,3,4; D:1,3,5}
I need to get this map:
{AnB:2; AnC:2,3; AnD:1,3; BnC:2,4; AnBnC:2; AnCnD:3;}
. Doing this recursively is not an option as for larger sets we run of heap space. So I am doing it iteratively by adding the next "layer" onto the existing layer. So to get AnBnC I take AnB and calculate the intersection with C. But this also means I take AnC and calculate the intersection with B which will both give the same result.

Thanks!

CAB CAB
Answer

I'm not sure about the answer to your direct question about which is faster, but if you're trying to optimize, I suggest avoid doing unnecessary set intersections. Something like;

intersectionKey = setA.key + setB.key;
if (!map.containsKey(intersectionKey)) {
    intersection = A | B;
    map.put(intersectionKey, intersection);
}