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