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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With