使用多个if语句或在后面加上许多其他if语句是否更有效? [英] is it more efficient to use multiple if statements or one with lots of else ifs after it?
问题描述
例如,许多if
和许多else if
在开始的一个if
之后.我在下面添加了一些伪代码.
As an example of lots of if
s and many else if
after one if
at the start. I have added some pseudo code below.
if (x=1)
print x;
if (x=2)
print x;
if (x=3)
print x;
或
if (x=1)
print x;
else if (x=2)
print x;
else if (x=3)
print x;
推荐答案
您的代码无法编译;如果您确实要检查条件,则需要使用==
代替=
;除效率外,还根据需求使用了这两种技术.您可以在以下情况下使用第一种情况:
Your code won't compile; if you really want to check for conditions you need to use ==
instead for =
; more than efficiency, these two techniques are used depending on the requirements. You can use the first case for the following scenario:
if (x==1)
//Do something
// 'x' may change here
if (x==2) // check for next condition
// Do another thing
// 'x' may change
if (x==3) // check for another condition
// Do something more
//'x' may change
如果x
的值未更改,则可以执行第二组代码.这样,一旦找到真实条件,您就可以跳过对其余条件的评估.考虑x=1
,因此它不会检查x==2
和x==3
,这样我们可以减少执行时间.
You can do the second set of code if the value for x
is not changing. So that you can skip evaluating the rest of conditions once a true condition is found. Consider x=1
So it won't check for x==2
and x==3
so that we can reduce the execution time.
x=1;
if (x==1) // Evaluates to true;
// Do Something
// Exit the if
else if (x==2) // will not check for this
//Do another thing
else if (x==3) // will not check for this
//Do another thing
If you have more entries to check you should use a switch instead of these two.
这篇关于使用多个if语句或在后面加上许多其他if语句是否更有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!