Koen Demonie
Koen Demonie

Reputation: 539

performance issue variable assignment

I am wondering, what scenario would be best ?

(Please bare with my examples, these are just small examples of the situation in question. I know you could have the exact same function without a result variable.)

A)

    public String doSomthing(){
       String result;
       if(condition){ result = "Option A";}
       else{ result = "Option B";}
       return result;
   }

B)

   public String doSomthing(){
       String result = "Option B";
       if(condition){ result = " Option A";}
       return result;
   }

Cause in scenario B: if the condition is met, Then you would be assigning result a value twice. Yet in code, i keep seeing scenario A.

Upvotes: 1

Views: 43

Answers (1)

Kelevandos
Kelevandos

Reputation: 7082

Actually, the overhead here is minimal, if any, considering the compiler optimisations. You would not care about it in a professional coding environment, unless you are writing a compiler yourself.

What is more important, considering (modern) programming paradigms, is the code style and readability.

Example A is far more readable, as it has a well-presented reason-outcome hierarchy. This is important especially for big methods, as it saves the programmer lots of analysis time.

Upvotes: 1

Related Questions