Salman Khalifa
Salman Khalifa

Reputation: 85

Does nesting in an empty else yield overhead?

Example 1:

if(some statement)
   .... //irrelevant code
else
   if(other statement)
      .....
   else
      .....

Example 2:

if(some statement)
   .... //irrelevant code
else if(other statement)
   ....
else
   ....

In my case, I would prefer to use example 1 to show that the nested if statements are related.

Is example 1 less efficient then example 2?

Upvotes: 3

Views: 116

Answers (1)

Maroun
Maroun

Reputation: 95948

The two codes are the same as this one:

if(some statement) .... else if(other statement) else

Performance has nothing to do with this, this is exactly the same code (The same bytecode will be generated), whereas readability does something to do with this, I prefer the first.

I advise you to have curly brackets even for one-line statements inside if and else blocks:

if(something) {
   doSomething();
} else if(something2()) {
   doSomething2();
} else {
   doSomething3();
}

Upvotes: 3

Related Questions