许多情况下的开关优化保证任何情况下的访问时间相等?(C++)

2022-01-19 00:00:00 optimization c switch-statement c++

我在这里看到了针对特定语言的答案,关于使用跳转表优化超过 5 种情况的开关,以保证任何情况下的恒定访问时间.
C/C++ 是这样吗?
它特别适用于 gcc 吗?视觉工作室?
如果没有,按发生频率排序是否有帮助?

I've seen answers here for specific languages, about switches with more than 5 cases being optimized with jump tables to guarantee constant access time for any case.
Is that so for C / C++?
Is it in particular for gcc? for visual studio?
If not, would sorting cases in order of occurrence frequency help?

推荐答案

该标准不保证 switch 语句将如何实现.我从未见过编译器生成哈希表,尽管有不少编译器会生成跳转表.除非我的记忆力比平时更差,否则当案例足够密集时(对于足够"的不同值),VS 和 gcc 都可以生成跳转表.不幸的是,几乎不可能说(甚至必须弄清楚)按出现频率排序会有所帮助 - 不仅编译器之间不同,甚至同一编译器的不同版本之间也是如此.

The standard doesn't guarantee anything about how the switch statement will be implemented. I've never seen a compiler produce a hash table, though quite a few will produce a jump table. Unless my memory is working even worse than usual, both VS and gcc can produce jump tables when the cases are sufficiently dense (for different values of "sufficiently"). Unfortunately, it's almost impossible to say (or necessarily even figure out) when sorting by frequency of occurrence will help -- it's different not only between compilers, but even between different versions of the same compiler.

相关文章