简体   繁体   中英

Java efficiency Hashmap get method

So my question is probably a bit basic and a bit of an overkill. But what I want to ask is whether it is more efficent to use the same Hashmap get method multiple times. Or to point an object on one of the get methods and then work with this temporary object. I wrote a little bit of code to visualize it.

    HashMap<String, MyClass> stringCounter = new HashMap<>();
    stringCounter.put(..., ...); // ...

    if(stringCounter.containsKey(name)) stringCounter.get(name).remove();
    else stringCounter.get(name).add();

    MyClass myClass = stringCounter.get(name);
    if(stringCounter.get(otherName).remove) myClass.remove();
    else myClass.add();

Quick answer : get your instance once, then work with it, this will be faster and cleaner to read also. When you get in the hashmap, internaly it does a lookup, the jvm may or may not detect that it could be optimized. But as you are not sure just

Object instance = map.get(key);
if(instance != null {
    instance.doThis();
    instance.doThat();
}

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