切换语句具有大量的案例 [英] Switch statement with huge number of cases

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

问题描述

如果开关有超过5000个 case ,会发生什么。有什么缺点,我们如何用更快的东西替换它?



注意:我不希望使用数组来存储案例,因为它是一样的。

解决方案

没有特别的理由认为你想要除switch / case语句之外的任何东西(事实上我会积极期望它毫无帮助)。编译器应该创建高效的调度代码,这可能涉及静态[稀疏]表和直接索引,二进制分支等的某种组合。它对案例的静态值有深入的了解,并且应该做一个很好的工作(在每次改变案例时重新调整它,而新的值与手工制作的方法不匹配 - 例如极不相同的值当你有一个漂亮的打包数组查找 - 可能需要重做代码或静默导致内存膨胀或性能下降)。



人们真的在乎这种事情当C试图赢得硬核程序员的时候...编译器负责生成好的代码。换一种方式 - 如果它不是(可测量的)破碎,不修复它。



更普遍的是,很好奇这种事情,并得到人们的想法关于替代品和它们的性能影响,但如果你真的关心和性能差异可能会对你的程序有用的差异(特别是如果分析建议),然后总是基准与你的程序做真正的工作。 p>

What happens if the switch has more than 5000 case. What are the drawbacks and how we can replace it with something faster?

Note: I am not expecting to use array to store cases as it's the same.

解决方案

There's no specific reason to think you'd want anything other than a switch/case statement (and indeed I'd actively expect it to be unhelpful). The compiler should create efficient dispatching code, which might involve some combination of static [sparse] table(s) and direct indexing, binary branching etc.; it's got insights into the static values of the cases and should do an excellent job (retuning it on the fly each time you change the cases, whereas new values that don't fit well with a hand-crafted approach - such as wildly differing values when you'd had a pretty packed array lookup - could require reworking of code or silently cause memory bloat or a performance drop).

People really cared about this kind of thing back when C was trying to win over hard-core assembly programmers... the compilers were held accountable for generating good code. Put another way - if it's not (measurably) broken, don't fix it.

More generally, it's great to be curious about this kind of thing and get people's ideas on alternatives and their performance implications, but if you really care and the performance difference could make a useful difference to your program (especially if profiling suggests it) then always benchmark with your program doing real work.

这篇关于切换语句具有大量的案例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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