If vs. Switch Speed(如果与开关速度)
问题描述
Switch 语句通常比等效的 if-else-if 语句更快(例如,在此 文章中描述) 由于编译器优化.
Switch statements are typically faster than equivalent if-else-if statements (as e.g. descibed in this article) due to compiler optimizations.
这种优化实际上是如何工作的?谁有好的解释?
How does this optimization actually work? Does anyone have a good explanation?
推荐答案
编译器可以在适用的地方构建跳转表.例如,当您使用反射器查看生成的代码时,您会看到对于字符串上的巨大开关,编译器实际上会生成使用哈希表来调度这些的代码.哈希表使用字符串作为键并将 case
代码作为值.
The compiler can build jump tables where applicable. For example, when you use the reflector to look at the code produced, you will see that for huge switches on strings, the compiler will actually generate code that uses a hash table to dispatch these. The hash table uses the strings as keys and delegates to the case
codes as values.
与许多链式 if
测试相比,这具有更好的运行时间,并且实际上即使对于相对较少的字符串也更快.
This has asymptotic better runtime than lots of chained if
tests and is actually faster even for relatively few strings.
这篇关于如果与开关速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果与开关速度


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