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.
这篇关于如果与开关速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果与开关速度


基础教程推荐
- 将数据集转换为列表 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03