So I find myself doing something like the following pattern often. Instead of:
if (map.containsKey(someKey)) {
Value someValue = map.get(someKey);
...
}
To not traverse the map twice (and since I know my map doesn't store nulls), I'll do:
Value someValue = map.get(someKey);
if (someValue != null) {
...
}
This seems to me to be a worthwhile pattern given that the Map
operations perform a decent number of operations and the optimizer, I assume, is not smart enough to optimize it away.
But then I find myself doing similar patterns in other situations. For example, should I store the someMethod()
result in a temporary variable instead of making the call twice? Clearly I can't call someMethod()
twice if there are side-effects but when does it make sense to only call it once from an optimization standpoint?
if (someObject.someMethod() != null) {
processSomehow(someObject.someMethod());
}
I know this borders on a "not constructive" question so I'm looking for answers that present some facts and references instead of just conjecture.
- When does it make sense to do this and when does it not?
- How should I evaluate the "cost" of the
someMethod()
to determine when a temporary variable should be used? - For simple methods such as get methods, might this get in the way of the hotspot compiler or the optimizer and actually produce less efficient code?
For posterity, I am not asking "how can I improve the speed of my existing program". I am trying to figure out "what pattern should I use when I write future code".
Thanks for any information.