【发布时间】:2012-12-30 19:43:32
【问题描述】:
可能重复:
What is the relative performance difference of if/else versus switch statement in Java?
给定以下两种方法:
public static int useSwitch(int i) {
switch (i) {
case 0:
return 1;
default:
return 0;
}
}
public static int useIf(int i) {
if (i == 0)
return 1;
return 0;
}
测试表明switch 的执行速度比if 版本稍快(在我的机器上每次调用1.4 纳秒)。
我一直认为,直到可以避免至少几个 ifs 之后,切换的好处才会发挥作用,
为什么switch 比单个if 快?
【问题讨论】:
-
你知道它们编译后的样子吗?也许你可以在那里找到答案。
-
@user1306322- 您必须更深入地研究 JVM 是如何解释或编译该字节码的。第一个代码可能会使用
lookupswitch或tableswitch指令,而第二个代码将使用正常跳转。让它们快速工作完全取决于 JVM。 -
您能发布您的基准测试代码吗?
-
@PatriciaShanahan 测试代码比较
nanoTime()和for (int i = 0; i < 999999; i++) x += useIf(i)(x被断言)
标签: java performance if-statement switch-statement