如果Else和多个If语句的比较

6

当我编写代码时,通常会使用多个if语句:

if(logicalCheck){
  ...
}

if(secondLogicalCheck){
  ...
}

我很少使用If Else。我知道使用我的方法意味着多个逻辑检查可能会被满足,而在if else链中只能发生一个。

我的问题是,在C、Java或JavaScript中使用一种方法是否有性能优势?使用多个if语句有什么特别的问题吗?


2
如果条件是互斥的,那么请使用 else if,这样可以避免多次条件检查。 - Tushar
3
请提供需要翻译的原文。 - Jongware
1
为什么我们在处理返回语句的条件时,使用if-else if 而不是多个if块? - Kasun Gamage
只有在你的语句中断或返回时它们才是等价的。 - shmosel
3个回答

14

如果仅使用if语句,则编译器或其他将测试所有条件,但如果使用else if(如果可能),则在通过任何条件后,下一个else if将不会被测试或检查。

if (age < 10){
   // do something
}
if (age < 20 && age > 10){
   // do something
}
if (age < 30 && age > 20){
   // do something
}

所有条件将被测试/比较

但在这种情况下

if (age < 10){
   // do something
}
else if (age < 20 && age > 10){
   // do something
}
else if (age < 30 && age > 20){
   // do something
}
如果年龄是5岁,只有第一个条件会被测试。

1
顺便提一下,如果条件测试非常简单,有或没有else,代码执行速度将非常快。但是,如果测试更加复杂,涉及文件I/O、数据库请求或其他操作,你应该使用else来避免不必要的执行。 - Prim

2
如果只有一个条件可能为真,使用 if else-if 可以节省一些条件的评估。由于评估条件可能很昂贵,在没有实际需要的情况下评估多个条件可能会在性能方面造成损失。
如果多个条件可以同时为真,则使用多个 if 语句或单个 if-else-if..else 结构取决于所需的逻辑 - 即如果有多个条件为真,您是否希望执行多个条件访问的块中的多个块。

0
使用条款如下:
如果您有多个独立的逻辑,用于对条件进行非相关限制或操作,则可以分别使用多个if语句:
if(conditionA){
    // do what suppose to do
}

if(conditionB){
    // do what suppose to do
}

. . .


如果您想要应用您所设定的条件,则应使用 if elseif else if 语句:

if(conditionA) {
        // do what suppose to do on conditionA
} else {
    // do what suppose to do if the conditionA doesn't satisfied.
}

if(conditionA) {
        // do what suppose to do on conditionA
} else if(conditionb) {
        // do what suppose to do on conditionB
}  else {
    // do what suppose to do if non of the conditions were satisfied.
}

顺便提一下,如果你想使用 if else if 链,最好使用 switch case 语句:
switch(true){
    case conditionA:
        // do what suppose to do on conditionA
        break;
    case conditionB:
        // do what suppose to do on conditionB
        break;
    default:
    // do what suppose to do if non of the conditions were satisfied.
}

你能解释一下为什么使用 switch case 语句比 if else if 链更好吗? - Gurnard
1
@Gurnard 我所说的“更好”与性能无关,而是为了提高代码的可读性。然而,在可能的情况下使用HashMap可以很大程度上提高性能,因为访问每个HashMap几乎是瞬间完成的。 - Morteza Tourani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接