subbu subbu - 9 months ago 44
Java Question

which one to choose between calling a function twice and storing the return value in a variable?

I have the following scenario.. and I come across the similar scenario many a times. Which is more preferable of the following two options?


String result = ( getDetails(...) == null ) ? "" : getDetails(...);


String returnValue = getDetails(...);
String result = ( returnValue == null ) ? "" : returnValue;

Which is more preferable and/or a good practice.?

Answer Source

Option-2: is better

Option-1: Results in extra method call and such cases should always be avoided unless getDetails(...) is a getter method (a one liner method which returns something)

If you dig down to micro optimization, a method call generally results in

  • allocation of stack for the method variables
  • jumping the instruction set

which are couple of many overheads. As many say, such performance optimization should be left to Compiler and the code should be written to be more readable.