if else vs java中的switch性能 [英] if else vs switch performance in 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;
但在交换机中,有一个break命令。我接近了吗?如果没有,你能解释它们之间的效率差异吗?
But in the switch, there is a break command. Is my approaching right? If not, could you explain the efficiency difference between them?
推荐答案
切换
perf优于 if else
,因为在切换的情况下会有一次评估。一旦它评估了交换机它就知道需要执行哪种情况,但是如果 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,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
这篇关于if else vs java中的switch性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!