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

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

问题描述

Java文档


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

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

AFAIK甚至交换机中的字符串在内部以区分大小写的方式使用 .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更快(但只有当不止一些字符串时才会显着)因为它首先使用 switch 字符串的 hashCode 来确定可能匹配的字符串子集。如果case标签中的多个字符串具有相同的hashCode,则JVM将执行对 equals 的顺序调用,即使case标签中只有一个字符串表示hashCode ,JVM需要调用等于来确认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天全站免登陆