Is there any significant difference between using if/else and switch-case in C#?(在 C# 中使用 if/else 和 switch-case 有什么显着区别吗?)
问题描述
在 C# 中使用 switch
语句与 if/else
相比有什么好处/坏处.除了代码的外观之外,我无法想象会有那么大的不同.
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?
推荐答案
SWITCH 语句仅在调试或兼容模式下生成与 IF 相同的程序集.在发布时,它将被编译成跳转表(通过 MSIL 'switch' 语句)- 这是 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#(与许多其他语言不同)也允许打开字符串常量——这有点不同.为任意长度的字符串构建跳转表显然是不切实际的,因此大多数情况下这种开关将被编译成 IF 堆栈.
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个左右,则优先选择SWITCH而不是IF,否则使用看起来更好的.
To sum it up, if number of conditions is more than 5 or so, prefer SWITCH over IF, otherwise use whatever looks better.
这篇关于在 C# 中使用 if/else 和 switch-case 有什么显着区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中使用 if/else 和 switch-case 有什么显着区别吗?


- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01