Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch optimization for many cases guarantees equal access time for any case? ( C++ )

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?

like image 415
Petruza Avatar asked Jan 25 '10 01:01

Petruza


2 Answers

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.

like image 106
Jerry Coffin Avatar answered Nov 06 '22 19:11

Jerry Coffin


For gcc's implementation see:

http://old.nabble.com/optimization-of-switch-statements-on-i386-to15366926.html#a15367662

like image 32
Sashmit Bhaduri Avatar answered Nov 06 '22 18:11

Sashmit Bhaduri