C ++ Switch Table Performance

Is the time used by the switch statement (or the transition table in compiled form) to "decide" where the jump is increased by the number of case es that it contains?

+4
source share
3 answers

It depends on the compiler and (usually) the values ​​you specify - if the values ​​are "dense" (that is, all or almost all of the values ​​in the range have cases in the switch statement), you usually get a table jump that takes the same time for all values ​​(in this range). If you have relatively rare values, it can compile code roughly equivalent to the if / then / else ladder, in which case adding more (sparse) case values ​​can increase the execution time.

+8
source

In fact, there is usually no hash table or any other O (1) lookup data structure in the compiled code (if you do not have only a small number of switches, then the compiler may decide to use transitions). In general, a large number of switches should exceed a large number of if statements, although usually you would not have enough cases to make it noticeable anyway.

+5
source

Why are you interested in this? This is a very low-level micro-optimization, which is unlikely to give any noticeable performance improvement unless you have a very evil algorithm with the last nanoseconds that are already squeezed out of it.

If you have a specific case where you have verified that switch really an important bottleneck, don’t ask us (what do we know about your compiler, memory, processor, etc ..?), But measure yourself using tools, which you use in the environment that the code should execute. In each other case, just continue coding and try writing code so that it is readable, and not for premature optimization.

-1
source

Source: https://habr.com/ru/post/1311966/


All Articles