Is using If, ElseIf, ElseIf better than using If, If, If?

Is there any difference between using

If(this) { } Else If(that) { } Else { } 

or using

 If(this) { } If(that) { } Else { } 

? Is it faster? Doesn't matter compiler or architecture?

+4
source share
5 answers

There is a huge difference in that the contents of this -block and that -block can be executed in the second form, while the first form allows you to execute at most one of them.

Compare these two Python snippets:

 x = 10 if x > 5: print "x larger than 5" elif x > 1: print "x larger than 1" else: print "x not larger than 1" # output: x larger than 5 

and

 x = 10 if x > 5: print "x larger than 5" if x > 1: # not using else-if anymore! print "x larger than 1" else: print "x not larger than 1" # output line 1: x larger than 5 # output line 2: x larger than 1 

As others have noted, you generally should not worry about performance between these changes as much as you should worry about correctness. However, since you asked ... everyone else is equal, the second form will be slower because the second condition needs to be evaluated.

But if you have not determined that the code written in this form is a bottleneck, you should not even think about optimization. When moving from the first form to the second, you will abandon the first if statement and return a forced evaluation of the second condition. Depending on the language, this is probably an extremely minor difference.

+19
source

Yes, in the first example, if it evaluates to true, and that the value is true, only the first block of code will be executed, while in the second example both of them will be.

They are not equivalent

+4
source

Yes.

In the first case: control-flow will only check the following condition if the current condition fails, but in the second case it checks all the conditions that arise.

In the first case, the Else part will be fulfilled only if all the previous conditions are not true. and in the second case, only if the last If condition does not work.

+3
source

it matters.

in the case of "this" and "that" are both true, both parts of the code will lead to something else.

+1
source

In the first code. it will check IF , if true, then execute its body, if false, then check ELSEIF , if that is true, to execute its body, if false, then execute else.

The second code, he will check IF , if true, then execute his body, if a lie does nothing. check 2 IF , if that is true, executing its body, if false, then execute the else body.

0
source

Source: https://habr.com/ru/post/1310486/


All Articles