在c#中使用switch语句和if/else语句的优缺点是什么?除了代码的外观,我无法想象有这么大的区别。
是否有任何原因导致最终的IL或相关的运行时性能会有根本的不同?
相关:什么是更快,开关上字符串或elseif上类型?
在c#中使用switch语句和if/else语句的优缺点是什么?除了代码的外观,我无法想象有这么大的区别。
是否有任何原因导致最终的IL或相关的运行时性能会有根本的不同?
相关:什么是更快,开关上字符串或elseif上类型?
当前回答
我的意见。大多数情况下,如果性能不是标准,那么代码的可读性就更重要了。如果If /else语句的数量太多,则使用switch语句会更好。
其他回答
如果你只使用If或else语句基解使用比较?操作符
(value == value1) ? (type1)do this : (type1)or do this;
你可以在开关中执行或程序
switch(typeCode)
{
case TypeCode:Int32:
case TypeCode.Int64:
//dosomething here
break;
default: return;
}
有三个理由支持这种转变:
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语句) 开始和结束他的工业生涯
我无法想象没有开关的生活。
根据这个链接,使用Switch和IF语句的迭代测试的IF和Switch比较,就像对于1,000,000,000次迭代,Switch语句花费的时间= 44.3秒,IF语句花费的时间= 48.0秒
也就是每秒20833333次迭代,所以,我们真的需要更专注吗,
附注:只是为了了解在少量条件下的性能差异。
编译器将把几乎所有内容都优化为相同的代码,只有微小的差异(Knuth,任何人?)
区别在于一个switch语句比串在一起的15个if else语句更简洁。
朋友不会让朋友叠加if-else语句。
我的意见。大多数情况下,如果性能不是标准,那么代码的可读性就更重要了。如果If /else语句的数量太多,则使用switch语句会更好。