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

好久不见. 提交于 2020-01-03 16:55:59

问题


Is there really any difference between using

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

or using,

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

? Does one execute any faster? Does the compiler or architecture make any difference?


回答1:


There's the huge difference that the contents of the this-block and the that-block can both be executed in the second form, whereas the first form allows at most one of those to be executed.

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 mentioned, you generally shouldn't be concerned about performance between these variations so much as you should be concerned about correctness. However, since you asked... all else being equal, the second form will be slower because the second conditional must be evaluated.

But unless you have determined that code written in this form is a bottleneck, it's not really worth your effort to even think about optimizing it. In switching from the first form to the second, you give up the jump out of the first if-statement and get back a forced evaluation of the second condition. Depending on the language, that's probably an extremely negligible difference.




回答2:


Yes, in your first example, if this evaluates to true and that evaluates to true, only the first code block will be executed, whereas in the second example, they both will.

They are not equivalent




回答3:


Yes.

In the First case: control-flow will only check the next condition if the current condition fails but in the second case it will check all conditions that come across.

In first case Else part will only be executed if all previous conditions fails to be true. and in the second case only if the last If condition fails.




回答4:


it makes a difference.

in case "this" and "that" are both true, both part of code will result something else.




回答5:


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

Second code it will check IF, if this is true then execute its body, if false do nothing. check 2nd IF if that is true that execute its body, if false then will execute body of else.



来源:https://stackoverflow.com/questions/2881560/is-using-if-elseif-elseif-better-than-using-if-if-if

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!