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

查看:21
本文介绍了switch 语句中的 String 如何比相应的 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 even String in 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 更快(但仅在字符串多于几个时才明显),因为它首先使用 hashCodeswitch 用来确定可能匹配的字符串子集的字符串的 code>.如果 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 语句中的 String 如何比相应的 if-else 语句更有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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