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?
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
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.
it makes a difference.
in case "this" and "that" are both true, both part of code will result something else.
The first one would execute faster when "If(this)" is true, because "If(that)" doesnt need to be evaluated. The second one must evaluate both in any case.
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.