有没有的if / else和开关的情况下在C#中使用的任何显著的区别?有的、显著、情况下、区别

2023-09-02 10:15:00 作者:正值青春、有何不可

有什么好处/缺点的if / else在C#使用开关语句与一个。我无法想象那里是那么大的差别,除了你的code可能的样子。

What is the benefit/downside to using a switch statement vs. an if/else in C#. I can't imagine there being that big of a difference, other than maybe the look of your code.

有什么原因导致IL或相关的运行时性能会是完全不同的?

Is there any reason why the resulting IL or associated runtime performance would be radically different?

推荐答案

要纠正斯科特的Wisniewski的回答(这是不对的每一个方面,但不知何故upvoted和接受)

To correct on 'Scott Wisniewski' answer (which is wrong on every aspect, but somehow got upvoted and accepted)

switch语句只产生在调试和兼容模式相同的组件,国际单项体育联合会。在版本,它会被编译成跳转表(通过MSIL'开关'语句) - 这是O(1)

SWITCH statement only produces same assembly as IFs in debug or compatibility mode. In release, it will be compiled into jump table (through MSIL 'switch' statement)- which is O(1).

C#(不像许多其他语言)也允许在字符串常量切换 - 这工作有点不同。这显然​​不实际搭建的任意长度的字符串跳表,因此经常这样的开关会被编译成国际单项体育联合会的协议栈。

C# (unlike many other languages) also allows to switch on string constants - and this works a bit differently. It's obviously not practical to build jump tables for strings of arbitrary lengths, so most often such switch will be compiled into stack of IFs.

但如果条件数量足够大,以支付费用,C#编译器将创建一个Hashtable对象,以字符串常量填充它,使该表后面跳查找。哈希表查找是不严格的O(1),并具有明显的恒定成本,但如果情况下的数目标签是大的,这将是显著快于比较每个字符串常量中的IF

But if number of conditions is big enough to cover overheads, C# compiler will create a HashTable object, populate it with string constants and make a lookup on that table followed by jump. Hashtable lookup is not strictly O(1) and has noticeable constant costs, but if number of case labels is large, it will be significantly faster than comparing to each string constant in IFs.

要概括起来讲,如果条件数量多于5左右,preFER切换中频,否则使用任何看起来更好。

To sum it up, if number of conditions is more than 5 or so, prefer SWITCH over IF, otherwise use whatever looks better.