Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local variable assignment to avoid multiple casts

Tags:

java

casting

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) {
    ...
  }
}
like image 975
Adamski Avatar asked Sep 17 '09 11:09

Adamski


4 Answers

I prefer creating the local variable rather than always casting because of readability issues. Code readability, for me (or other developers working on the same code), is an important issue.

Worrying about performance at this stage strikes me as an example of the "premature optimization" pattern.

like image 98
SteveD Avatar answered Oct 12 '22 10:10

SteveD


Definitely go with the first. The performance difference is likely to be irrelevant, but the readability is definitely improved.

In addition to removing the casts, it also means you get to use a different name - after all, you now know more about this variable, so it may well make sense to give it a more specific name. That's not always the case, but it can be. The "introduce local variable for the sake of naming a value" refactoring technique is an underappreciated one, even without the casts...

like image 24
Jon Skeet Avatar answered Oct 12 '22 10:10

Jon Skeet


I prefer the first, as it looks more clean. The second is starting to look like Lisp. But it's just a personal opinion.

like image 20
João Silva Avatar answered Oct 12 '22 09:10

João Silva


I'd say the important thing is not to optimise prematurely. If there is an overhead to casting, it's likely to be so small that it would be effectively unnoticeable in practice. Unless this code snippet formed the majority of your application's CPU time, I don't think you'd see any measurable performance difference between the two.

Consequently I'd also go for the first option as it looks cleaner and is easier to understand and modify - much more important than executing a couple of clock cycles faster in 99.99% of situations.

like image 20
Andrzej Doyle Avatar answered Oct 12 '22 11:10

Andrzej Doyle