使用switch语句与使用if30个unsigned枚举的语句的最佳实践是什么,其中大约10个具有预期的操作(目前是相同的操作).需要考虑性能和空间,但并不重要.我已经抽象了代码片段,所以不要因为命名惯例而讨厌我.
switch 声明:
// numError is an error enumeration type, with 0 being the non-error case
// fire_special_event() is a stub method for the shared processing
switch (numError)
{
case ERROR_01 : // intentional fall-through
case ERROR_07 : // intentional fall-through
case ERROR_0A : // intentional fall-through
case ERROR_10 : // intentional fall-through
case ERROR_15 : // intentional fall-through
case ERROR_16 : // intentional fall-through
case ERROR_20 :
{
fire_special_event();
}
break;
default:
{ …Run Code Online (Sandbox Code Playgroud) 我对速度感到好奇switch,认为它"非常"快,但是我有一个测试用例,似乎显示单个开关大约和4个if测试一样快,当我预期(没有坚实的理由)它和1次测试一样快.这里有两种方法我写的比较switch有if:
public static int useSwitch(int i) {
switch (i) {
case 1: return 2;
case 2: return 3;
case 3: return 4;
case 4: return 5;
case 5: return 6;
case 6: return 7;
default: return 0;
}
}
public static int useIf(int i) {
if (i == 1) return 2;
if (i == 2) return 3;
if (i == 3) return 4;
if (i == 4) return 5;
if (i == …Run Code Online (Sandbox Code Playgroud) 我想知道使用if语句或switch之间是否存在任何效率差异.例如:
if(){
//code
}
else if(){
//code
}
else{
//code
}
Run Code Online (Sandbox Code Playgroud)
我相信程序需要去检查所有if语句,即使第一个if语句是真的.
switch(i){
case 1:
//code
break;
case 2:
//code
break;
Run Code Online (Sandbox Code Playgroud)
但是在交换机中,有一个break命令.我接近了吗?如果没有,你能解释一下它们之间的效率差异吗?