如果对开关速度 [英] If vs. Switch Speed

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

问题描述

switch语句通常快于等价的if-else-if语句(如如在此文章 descibed)由于编译器优化。

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?

推荐答案

编译器可以建立跳转表适用。例如,当您使用反射来看看产生的code,你会看到,对字符串巨大的开关,编译器将实际产生一个使用哈希表来调度这些code。哈希表使用字符串作为键,并委托给情况 codeS的值。

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.

这有渐进比很多的链接如果测试更好的运行时和实际上是更快的甚至相对弦数。

This has asymptotic better runtime than lots of chained if tests and is actually faster even for relatively few strings.

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

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