Slide 23
Slide 23 text
Avoid Unnecessary Map Lookups
Use Variables!
// SLOW: two lookup on the same key
if (myMap.contains("key")) {
MyObject v = myMap.get("key");
// ...
}
final MyObject v = myMap.get("key");
if (v != null) { // equivalent to myMap.contains("key")
// ...
}
Avoid one lookup
final HashMap myMap = new HashMap<>();
// ...
for (int i = 0; i < N; ++i) {
// SLOW: each iteration there are 3 lookups for the same key
final String key = "key-" + i;
myMap.get(key).doSomething();
myMap.get(key).doMore(myMap.get(key).getData());
}
for (int i = 0; i < N; ++i) {
final MyObject value = myMap.get("key-" + i);
value.doSomething();
value.doMore(value.getData());
}
Use Variables, to Avoid Extra Lookups
final Map myMap;
// ...
final MyObject obj;
if (myMap.containsKey(key)) {
// if present, get the object
obj = myMap.get(key);
} else {
// not present, compute the new object
obj = new MyObject();
// add to it the map
myMap.put(key, obj);
}
obj.doStuff() // do something with the object
final Map myMap;
// ...
MyObject obj = myMap.computeIfAbsent(key, k -> new MyObject());
obj.doStuff() // do something with the object
Use Compute If Absent