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 语句更有效?


- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01