0

Take the following code snap for example:

public int demoMethod(){
    SomeClass object= getItFromSomewhere();
    return object.getResult();
}

also we can directly return getItFromSomewhere().getResult(). My question is whether the definition of "object" will low down the performance? And in some case, maybe the temporary local variable is very complicated, such as

SomeClass object =  otherClassObject.getMethod1().getMethod2().getMethod3().getMethod4();
return object.getMethod5();

If I don't use the temporary "object", the statement will be very difficult to read, how about you guys deal with this case?

David Pilkington
  • 13,528
  • 3
  • 41
  • 73
jason
  • 364
  • 1
  • 3
  • 10

2 Answers2

2

Afaik will be completely removed by jit. So there should not be any impact on performance introducing additional local variables to simplify expressions.

PS: The long expression, a.d.b.c is called a 'train wreck' by uncle bob. They are hard to read and a PITA to debug when you get an exception like a NPE.

pveentjer
  • 10,545
  • 3
  • 23
  • 40
1

As a general rule (in my opinion, but I trust I am not alone), your code should be optimized for readability before any other kind of optimization. This will allow other programmers to improve it later on, if needed. A very fast but unreadable code quickly becomes useless as nobody is able to make changes to it. Also, trust the compilers (javac and the JIT): they know how to rewrite your code to remove unused statements, like a variable that is not actually necessary.

Then, if speed is an issue, you should try to improve it by choosing more appropriate data structures (especially containers) and algorithms.

Lastly, if speed is still an issue (very rare nowadays), you should seek the advice of a specialist. There are people who do wonders with code that is seemingly efficient to begin with, but this is not something the average developer should do on a daily basis.

Community
  • 1
  • 1
Zoyd
  • 3,449
  • 1
  • 18
  • 27