Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

if-statement

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?

like image 607
PICyourBrain Avatar asked Nov 27 '22 18:11

PICyourBrain


2 Answers

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.

like image 150
Mark Rushakoff Avatar answered Jun 05 '23 17:06

Mark Rushakoff


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

like image 28
bravocharlie Avatar answered Jun 05 '23 18:06

bravocharlie