How is String in switch statement more efficient than corresponding if-else statement?(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 更快(但仅在字符串多于几个时才明显),因为它首先使用 hashCode
switch
用来确定可能匹配的字符串子集的字符串的 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 语句更有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:switch 语句中的 String 如何比相应的 if-else 语句更有效?


基础教程推荐
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01