简体   繁体   English

if else vs开关在Java中的性能

[英]if else vs switch performance in java

I'd like to know if there is any efficiency difference between using if statement or switch. 我想知道使用if语句或switch之间是否有效率差异。 For example: 例如:

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

I believe that program needs to go and check all of the if statement even if the first if statement was true. 我认为,即使第一个if语句为true,程序也需要检查所有if语句。

switch(i){

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

But in the switch, there is a break command. 但是在开关中,有一个break命令。 Is my approaching right? 我的对吗? If not, could you explain the efficiency difference between them? 如果没有,您能否解释一下两者之间的效率差异?

Switch perf is better than if else as in case of switch there will be one time evaluation . Switch PERF优于if else在开关的情况下,会有一个时间的评价。 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. 一旦评估了该开关,它便知道需要执行哪种情况,但是在if else情况下, if else情况最糟,则必须经过所有条件。

The longer the list condition, better will be switch performance but for shorter list (just two conditions), it can be slower also 列表条件越长,切换性能越好,但是对于较短的列表(仅两个条件),它也会变慢

From Why switch is faster than if 为什么切换比如果更快

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 通过切换,JVM加载要比较的值并遍历值表以查找匹配项,这在大多数情况下更快

Switch is faster. Switch速度更快。

Imagine you are at an intersection, with many paths. 想象一下,您正处在交叉路口,有很多路径。 With switch , you go to the right path at the first time. 使用switch ,您可以在第一时间转到正确的路径。

With if , then you have to try all the paths before you find the right one. if使用if ,则必须先尝试所有路径,然后才能找到正确的路径。

Use switch whenever possible. 尽可能使用switch

Of course, for computer this difference is very small that you don't even notice. 当然,对于计算机,这种差异很小,您甚至都不会注意到。 But yeah, you get the point. 但是,是的,您明白了。

I think the code is quite clear. 我认为代码很清楚。 With if, you have to check each case and after case by case (in the worst case, last return gives back the result). 使用if时,您必须检查每种情况,然后逐项检查(在最坏的情况下,最后一次返回将返回结果)。 With switch, some kind like a special byte code checking and jump to the correct case to return. 使用switch时,诸如特殊字节码检查之类的某种跳转到正确的情况以返回。 So the switch is a bit faster than the if statement. 因此,该开关比if语句快一点。 However, I think we need to focus on the way we implement for easier to read. 但是,我认为我们需要专注于实现方式,以便于阅读。 In some simple case, the if is also a choice to write code. 在某些简单的情况下,if也是编写代码的一种选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM