如果与切换速度 [英] If vs. Switch Speed

查看:17
本文介绍了如果与切换速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于如果与切换速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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