Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 !

like image 318
dnlmax Avatar asked Nov 09 '10 22:11

dnlmax


2 Answers

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

like image 181
John Kugelman Avatar answered Nov 14 '22 23:11

John Kugelman


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.

like image 40
uckelman Avatar answered Nov 14 '22 23:11

uckelman