subbu
subbu

Reputation: 489

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.?

Upvotes: 5

Views: 2415

Answers (5)

sanbhat
sanbhat

Reputation: 17622

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.

Upvotes: 1

Jagannath Behera
Jagannath Behera

Reputation: 1

option-2 will be always optimized one what ever you wrote in the calling function. Even if you are writing any in-build function or expression two times it will take fraction of section more than option-2.

Upvotes: 0

joe776
joe776

Reputation: 1116

I'd prefer the second option because it is more readable, especially when using the ternary operator.

If it is a problem or not to call getDetails(...) twice depends on your method. If it is a simple getter, the JVM might optimize the call and directly use the value so storing it in a local variable does not make a difference.
If it is a more complex method, e.g. a query to the database, I would definitely store the result in a local variable.

Generally speaking: Care about code readability first! If you find performance problems later on, try optimizing then.

Upvotes: 1

Tala
Tala

Reputation: 8928

If you have to do that check for every call of getDetails then the best way would be getDetails method to return "" in cases when you return null.

Also calling the same method twice (which is probably idempotent in your case) is not a good practice even if it is very simple.

Please read this java-how-expensive-is-a-method-call. Main idea is don't do premature optimization, but you should get used to these simple cases when you can write better code

Upvotes: 3

Suresh Atta
Suresh Atta

Reputation: 121998

Imho The second one is better because it's avoiding calling getDetails(...) method twice.

Upvotes: 4

Related Questions