subbu subbu - 8 days ago 5
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?

Option-1:

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


Option-2:

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


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

Answer

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.