switch 语句中的字符串如何比相应的 if-else 语句更有效? [英] How is String in switch statement more efficient than corresponding if-else statement?

查看:37
本文介绍了switch 语句中的字符串如何比相应的 if-else 语句更有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 文档

Java 编译器从使用 String 对象的 switch 语句生成的字节码通常比从链接的 if-then-else 语句生成的字节码效率更高.

The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

AFAIK 甚至 String 在 switch 内部以区分大小写的方式使用 .equals() .那么它们在这种情况下意味着什么效率.更快的编译?更少的字节码?更好的性能?

AFAIK even String in switch uses .equals() internally in a case sensitive manner. So what efficiency do they mean in this context. Faster compilation? Less bytecodes ? better performance?

推荐答案

使用 switch 语句比 equals 更快(但只有在字符串多于几个时才明显),因为它首先使用了 hashCode 切换 以确定可能匹配的字符串子集的字符串的代码>.如果 case 标签中有多个字符串具有相同的 hashCode,JVM 将执行对 equals 的顺序调用,即使 case 标签中只有一个字符串是 hashCode,JVM 也需要调用equals 来确认 case 标签中的字符串确实等于 switch 表达式中的字符串.

Using a switch statement is faster than equals (but only noticeably when there are more than just a few strings) because it first uses the hashCode of the string that switch on to determine the subset of the strings that could possibly match. If more than one string in the case labels has the same hashCode, the JVM will perform sequential calls to equals and even if there is only one string in the case labels that a hashCode, the JVM needs to call equals to confirm that the string in the case label is really equal to the one in the switch expression.

在 String 对象上切换的运行时性能与在 HashMap 中的查找相当.

The runtime performance of a switch on String objects is comparable to a lookup in a HashMap.

这段代码:

public static void main(String[] args) {
    String s = "Bar";
    switch (s) {
    case "Foo":
        System.out.println("Foo match");
        break;
    case "Bar":
        System.out.println("Bar match");
        break;
    }
}

被内部编译成这样一段代码并执行:

Is internally compiled to and executed like this piece of code:

(不是字面意思,但如果你反编译这两段代码,你会看到完全相同的动作序列发生)

(not literally, but if you decompile both pieces of code you see that the exact same sequence of actions occurs)

final static int FOO_HASHCODE = 70822; // "Foo".hashCode();
final static int BAR_HASHCODE = 66547; // "Bar".hashCode();

public static void main(String[] args) {
    String s = "Bar";
    switch (s.hashCode()) {
    case FOO_HASHCODE:
        if (s.equals("Foo"))
            System.out.println("Foo match");
        break;
    case BAR_HASHCODE:
        if (s.equals("Bar"))
            System.out.println("Bar match");
        break;
    }
}

这篇关于switch 语句中的字符串如何比相应的 if-else 语句更有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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