在c#中使用switch语句和if/else语句的优缺点是什么?除了代码的外观,我无法想象有这么大的区别。

是否有任何原因导致最终的IL或相关的运行时性能会有根本的不同?

相关:什么是更快,开关上字符串或elseif上类型?


当前回答

我的意见。大多数情况下,如果性能不是标准,那么代码的可读性就更重要了。如果If /else语句的数量太多,则使用switch语句会更好。

其他回答

通常它看起来会更好——也就是更容易理解发生了什么。考虑到性能上的好处最少,代码的视图是最重要的区别。

因此,如果if/else看起来更好,就使用它,否则使用switch语句。

题外话,但我经常担心(更经常看到)if/else和switch语句用太多的情况变得太大。这些通常会损害可维护性。

常见的罪魁祸首包括:

在多个if语句中执行太多操作 案例陈述多得人类无法分析 if求值中的条件太多,以至于不知道要寻找什么

修复:

提取到方法重构。 使用带有方法指针的Dictionary而不是大小写,或者使用IoC来增加可配置性。方法工厂也很有帮助。 提取条件到自己的方法

实际上,switch语句更有效。编译器会将其优化为一个查找表,而使用if/else语句则不行。缺点是switch语句不能与变量值一起使用。

你不能:

switch(variable)
{
   case someVariable:
   break;
   default:
   break;
}

它必须是:

switch(variable)
{
  case CONSTANT_VALUE:
  break;
  default:
  break;
}

有三个理由支持这种转变:

A compiler targeting native code can often compile a switch statement into one conditional branch plus an indirect jump whereas a sequence of ifs requires a sequence of conditional branches. Depending on the density of cases a great many learned papers have been written about how to compile case statements efficiently; some are linked from the lcc compiler page. (Lcc had one of the more innovative compilers for switches.) A switch statement is a choice among mutually exclusive alternatives and the switch syntax makes this control flow more transparent to the programmer then a nest of if-then-else statements. In some languages, including definitely ML and Haskell, the compiler checks to see if you have left out any cases. I view this feature as one of the major advantages of ML and Haskell. I don't know if C# can do this.

一个趣闻:在托尼·霍尔接受终身成就奖的演讲中,我听到他说,在他职业生涯中所做的所有事情中,有三件事是他最自豪的:

发明快速排序 发明switch语句(Tony称之为case语句) 开始和结束他的工业生涯

我无法想象没有开关的生活。

我认为,不只是c#,而是所有基于C的语言:因为切换仅限于常量,所以使用“跳转表”可以生成非常高效的代码。C用例实际上是一个很好的老式FORTRAN计算GOTO,但c#用例仍然是针对常量进行测试。

优化器不可能生成相同的代码。考虑,例如,

if(a == 3){ //...
} else if (a == 5 || a == 7){ //...
} else {//...
}

因为这些是复合布尔值,生成的代码必须计算一个值,然后短路。现在考虑一下

switch(a){
   case 3: // ...
    break;
   case 5:
   case 7: //...
    break;
   default: //...
}

这可以编译成

BTABL: *
B3:   addr of 3 code
B5:
B7:   addr of 5,7 code
      load 0,1 ino reg X based on value
      jump indirect through BTABL+x

因为你隐式地告诉编译器它不需要计算OR和相等测试。