dnlmax
dnlmax

Reputation: 113

What is better? if..else or multiple simple if

talking about java performance .. what is better? if..else or multiple simple if

if( condition ) {
  some_code;
  return value;
}
else if( condition ) {
  some_code;
  return value;
}
else if( condition ) {
  some_code;
  return value;
}
else {
  some_code;
  return value;
}

or

if( condition ) {
  some_code;
  return value;
}

if( condition ) {
  some_code;
  return value;
}

if( condition ) {
  some_code;
  return value;
}

some_code;    
return value;

Interested in your thoughts

Thnx !

Upvotes: 7

Views: 7888

Answers (5)

uckelman
uckelman

Reputation: 26234

The if...else example you give doesn't need the returns if this is in a function with no return value. In that case, the if...else will be easier to read.

Furthermore, the if...else should be preferred because it makes explicit that these cases are mutually exclusive.

If there's a performance difference here, then your compiler/interpreter sucks.

Upvotes: 1

Donald
Donald

Reputation: 1738

I would not worry about performance here as much as code readability and maintainability. As was mentioned, the performance will be essentially identical after the code is compiled.

It is my preference to be more explicit about my conditions, instead of allowing behavior to implicitly "fall through".

Also, the single if will not be evaluated any faster than the if else. The else path will never be checked if the case is true.

Upvotes: 0

Alan Geleynse
Alan Geleynse

Reputation: 25139

Depends on the situation.

If the conditions are mutually exclusive, use else. This will cause Java to not check any of the conditions after the one that is found to be true.

If they are not mutually exclusive, then using a list of if without else could cause multiple cases to occur.

In your case, with returns in each, the performance will be the same because the same number of comparisons will need to be done no matter what.

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361605

There is no difference, performance-wise. Choose the most readable option, which could be either depending on what the code does.

In general do not worry about these micro-optimizations. Optimization should only come after you've determined there is a performance problem that needs to be fixed.

"We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." —Donald Knuth

Upvotes: 16

MartinodF
MartinodF

Reputation: 8254

I'm confident a single if would be better, because whenever a true condition is encountered, it can safely skip the other else alternatives since they won't be executed. If you used multiple ifs, all the subsequent conditions would have to be evaluated anyway (even if, like I think you're supposing, they would be mutually exclusive).

Upvotes: 0

Related Questions