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

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

问题描述

许多 Java 书籍将 switch 语句描述为比 if else 语句更快.但我没有发现任何地方为什么 switch 比 if 快.

Lots of Java books describe the switch statement as being faster than the if else statement. But I did not find out anywhere why switch is faster than if.

我有一种情况,我必须从两项中选择一项.我可以使用任何一种使用

I have a situation I have to choose any one item out of two. I can use either use

switch (item) {
    case BREAD:
        //eat Bread
        break;
    default:
        //leave the restaurant
}

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

考虑 item 和 BREAD 是一个常量 int 值.

considering item and BREAD is a constant int value.

在上面的例子中,哪个动作更快,为什么?

推荐答案

因为有特殊的字节码可以在很多情况下进行高效的 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.

这篇关于为什么 switch 比 if 快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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