optimizing case-statement execution

raymond@harp.ecn.purdue.edu (Ray Kamin)
Sun, 22 Nov 1992 19:18:31 GMT

          From comp.compilers

Related articles
optimizing case-statement execution raymond@harp.ecn.purdue.edu (1992-11-22)
Re: optimizing case-statement execution chased@rbbb.Eng.Sun.COM (1992-11-23)
Re: optimizing case-statement execution erspert@athena.mit.edu (1992-11-25)
Re: optimizing case-statement execution nr@volkl.Princeton.EDU (1992-11-25)
Re: optimizing case-statement execution wtyler@adobe.com (1992-11-27)
Re: optimizing case-statement execution pardo@cs.washington.edu (1992-12-04)
Re: optimizing case-statement execution krste@ICSI.Berkeley.EDU (1992-12-05)
| List of all articles for this month |

Newsgroups: comp.compilers
From: raymond@harp.ecn.purdue.edu (Ray Kamin)
Organization: Purdue University Engineering Computer Network
Date: Sun, 22 Nov 1992 19:18:31 GMT
Keywords: C, code, optimize, question, comment

How do compilers (in my case gcc v2.2.2) handle large switch statements?
I have a 120 way switch in my code. I looked at the sparc assembly code
produced by gcc and it apparently doesn't use any sort of jump table, but
merely does sequential comparisons and branches.

With this in mind, I rewrote the code with each 'case' statement as a
separate function. I then created a pseudo jump table with function
pointers to each of these functions. That is, I call:


after setting the pointers as:

    case_fun[0] = &case0;
    case_fun[10] = &case10;
    case_fun[31] = &case31;

The code is working correctly, however, it is not any faster at all. Does
anyone have any insight into this, or how this should be written for


[There are three general ways to generate code for a switch: a jump table,
which is appropriate if the cases are numerically close to each other, a
binary-compare and branch tree if the set of cases is large and sparse, and
a sequential compare and branch otherwise. I'd expect that the overhead of
a procedure call would swamp any gain in indirecting through a table, if the
time spent in this part of your program is in fact large enough to make any
difference. If you really need speed, GCC lets you create arrays of labels
to use like a Fortran computed GOTO, but that is of course ugly and not very
portable. -John]

Post a followup to this message

Return to the comp.compilers page.
Search the comp.compilers archives again.