Why we use if, else if instead of multiple if block if the body is a return statement

if-elseif-else statements stop doing comparisons as soon as it finds one that’s true. if-if-if does every comparison. The first is more efficient.

Edit: It’s been pointed out in comments that you do a return within each if block. In these cases, or in cases where control will leave the method (exceptions), there is no difference between doing multiple if statements and doing if-elseif-else statements.

However, it’s best practice to use if-elseif-else anyhow. Suppose you change your code such that you don’t do a return in every if block. Then, to remain efficient, you’d also have to change to an if-elseif-else idiom. Having it be if-elseif-else from the beginning saves you edits in the future, and is clearer to people reading your code (witness the misinterpretation I just gave you by doing a skim-over of your code!).

Leave a Comment