if else 与 java 中的 switch 性能

2022-01-19 00:00:00 if-statement switch-statement java

我想知道使用 if 语句或 switch 之间是否有任何效率差异.例如:

I'd like to know if there is any efficiency difference between using if statement or switch. For example:

if(){
//code
}
else if(){
//code
}
else{
//code
}

我认为即使第一个 if 语句为真,程序也需要检查所有 if 语句.

I believe that program needs to go and check all of the if statement even if the first if statement was true.

switch(i){

case 1:
//code
break;
case 2:
//code
break;

但是在switch里面,有一个break命令.我的接近正确吗?如果不是,您能解释一下它们之间的效率差异吗?

But in the switch, there is a break command. Is my approaching right? If not, could you explain the efficiency difference between them?

推荐答案

Switch perf 比 if else 要好,因为在 switch 的情况下会有一次评估.一旦它评估了开关,它就知道需要执行哪种情况,但在 if else 的情况下,它必须通过所有条件以防最坏的情况.

Switch perf is better than if else as in case of switch there will be one time evaluation . Once it evaluated the switch it knows which case needs to be executed but in case of if else it has to go through all conditions in case of worst scenario.

列表条件越长,切换性能越好,但对于较短的列表(只有两个条件),它也可能更慢

The longer the list condition, better will be switch performance but for shorter list (just two conditions), it can be slower also

来自 为什么 switch 比 if 快

通过 switch,JVM 加载要比较的值并迭代查找匹配的值表,在大多数情况下更快

With switch the JVM loads the value to compare and iterates through the value table to find a match, which is faster in most cases

相关文章