为什么切换比if更快 [英] Why switch is faster than if

查看:135
本文介绍了为什么切换比if更快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在java中发现很多书说switch语句比if语句快。但是我没有找到哪里说为什么开关比更快。

I have found lots of books in java saying switch statement is faster than if else statement. But I didnot find antwhere saying why switch is faster than if.

我有一种情况我必须选择两个中的任何一项我可以使用以下任何一种方式

I have a situation i have to choose any one item out of two i can use either of the following way

switch(item){

case BREAD:
     //eat Bread
break;
default:
    //leave the restaurant

}

或使用if语句,如下所示

or using if statement like the following

if(item== BREAD){
//eat Bread
}else{
//leave the restaurant
}

考虑项目和BREAD是常数int值

在上面的例子中,行动更快,为什么?

推荐答案

因为有很多特殊字节码可以在很多情况下进行有效的switch语句评估。

Because there are special bytecodes that allow efficient switch statement evaluation when there are a lot of cases.

如果使用IF语句实现,则需要检查,跳转到下一个子句,检查,跳转到下一个子句等等。使用switch,JVM加载值进行比较并迭代值表以查找匹配,这在大多数情况下更快。

If implemented with IF-statements you would have a check, a jump to the next clause, a check, a jump to the next clause and so on. 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更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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