使用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) 担心我的网络应用程序的性能,我想知道哪个"if/else"或switch语句在性能方面更好?
我在java中发现很多书说switch语句比if语句更快.但我没有找到说明为什么开关比如果更快的地方.
我有一种情况我必须选择两个中的任何一项我可以使用以下任一方式
switch(item){
case BREAD:
//eat Bread
break;
default:
//leave the restaurant
}
Run Code Online (Sandbox Code Playgroud)
或使用if语句如下
if(item== BREAD){
//eat Bread
}else{
//leave the restaurant
}
Run Code Online (Sandbox Code Playgroud)
考虑项目和BREAD是常量int值
在上面的例子中,哪个更快,为什么?