if else 与 java 中的 switch 性能 [英] if else vs switch performance in java

查看:20
本文介绍了if else 与 java 中的 switch 性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用 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

这篇关于if else 与 java 中的 switch 性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆