There was recently a question asking whether it was a good idea in Java to assign the results of calling a getter to a local variable to avoid multiple calls to the same accessor. I can't find the original post but the consensus seemed to be that this generally isn't necessary as Hotspot will optimise away the method call overhead anyway.
However, what is the view on employing this technique to avoid multiple casts? At the moment I'm faced with a choice between:
if (a instanceof Foo) {
// Cast once and assign to local variable.
Foo foo = (Foo)a;
if (foo.getB() == 1 && foo.getC() == 2) {
...
}
}
OR
if (a instanceof Foo) {
// Cast twice making code compact but possibly less readable.
// Also, is there an overhead in multiple casts?
if (((Foo)a).getB() == 1 && ((Foo)a).getC() == 2) {
...
}
}