What's better? if ... or a few simple ones if

talk about Java performance. What's better? if..sse or a few simple ones 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!

+6
java performance if-statement
source share
5 answers

There is no difference in performance. Choose the most readable parameter, which can be either depending on what the code does.

In general, do not worry about these micro-optimizations. Optimization should appear only after you have determined that a performance problem should be fixed.

"We have to forget about little efficiency, say, about 97% of the time: premature optimization is the root of all evil." Donald whip

+16
source share

If you do not need an if ... else argument, return if it is in a function without a return value. In this case, if ... else it will be easier to read.

In addition, if ... else is preferable because it explicitly indicates that these cases are mutually exclusive.

If there is a difference in performance, then your compiler / interpreter sucks.

+1
source share

I am sure that one if will be better, because whenever a true condition is met, it can safely skip other else alternatives, since they will not be fulfilled. If you used multiple if s, all of the following conditions would have to be evaluated anyway (even if, as I think, you would consider them to be mutually exclusive). A.

0
source share

Depends on the situation.

If the conditions are mutually exclusive, use else . This will cause Java to fail to check any conditions after the found value is true.

If they are not mutually exclusive, then using an if list without others can lead to several cases.

In your case, with a return in each of them, the performance will be the same, since you will need to perform the same number of comparisons no matter what.

0
source share

I would not worry about performance here, as the readability of the code and maintainability. As already mentioned, the performance will be essentially identical after compiling the code.

I prefer to be more explicit in my conditions, rather than letting the behavior implicitly "fail."

In addition, the single if will not be evaluated faster than if. The else path will never be checked if true.

0
source share

All Articles