在 C# 中使用 if/else 和 switch-case 之间有什么显着区别吗? [英] Is there any significant difference between using if/else and switch-case in C#?

查看:39
本文介绍了在 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 相同的程序集.在release中,会被编译成跳转表(通过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 之间有什么显着区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆