Search code examples
javahashmap

For HashMap, is it more efficient to use compute() or put()


I have tried looking around for a while but I can't find a concrete answer and still am having some trouble understanding exactly what the compute method for HashMap does.

The way I understand it at the moment is that compute will allow you to manipulate the value but not set it to a new value (like where the garbage collector will have to get rid of the old object) while put will just get rid of the old object and set it (like going x = new Something).

If my understanding of this is wrong, please tell me, but regardless, is the compute method more efficient in general? Should I use this over put whenever possible or is it only used in certain situations?


Solution

  • Use put if you want to set a new value unconditionally. Use compute if you want to compute a new value based on the existing value in the map. You have the option of either changing it to a new value or removing it from the map.

    The documentation for compute states that:

    The default implementation is equivalent to performing the following steps for this map:

    V oldValue = map.get(key);
    V newValue = remappingFunction.apply(key, oldValue);
    if (newValue != null) {
        map.put(key, newValue);
    } else if (oldValue != null || map.containsKey(key)) {
        map.remove(key);
    }
    return newValue;
    

    It's more complicated than a simple put:

    1. It calls get to retrieve the current value.
    2. It calls the supplied remapping function to convert it to a new value.
    3. It either calls put to overwrite the old value or remove to remove it depending on whether the new value is null or not.

    Since ultimately it ends up calling put, compute has more steps and is slower. If put meets your needs—you don't care what's in the map, you just want to set a key to a value—use put.