<分区>
Possible Duplicate:
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
更快?