简体   繁体   中英

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} {A:1,2,3; B:2,4,6; C:2,3,4; D:1,3,5} {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;} {AnB:2; AnC:2,3; AnD:1,3; BnC:2,4; AnBnC:2; AnCnD:3;} {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!

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);
}

It depends, which Map you are using?

https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#put(K,%20V)

The Map.put API does return the previous value. Thus, the put() API self must be expensive than get(), which must be expensive than contains().

In short, just .put will be faster for basic HashMap / TreeMap implementation.

However, it could be an exception for ConcurrentMap which their implementation may try to optimize thread-local or avoid locking overhead in multi-thread environment.

BTW, but if I were you. I will use BitSet to optimize memory usage and performance if possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM