home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.compilers
- Path: sparky!uunet!world!iecc!compilers-sender
- From: raymond@harp.ecn.purdue.edu (Ray Kamin)
- Subject: optimizing case-statement execution
- Reply-To: raymond@harp.ecn.purdue.edu (Ray Kamin)
- Organization: Purdue University Engineering Computer Network
- Date: Sun, 22 Nov 1992 19:18:31 GMT
- Approved: compilers@iecc.cambridge.ma.us
- Message-ID: <92-11-126@comp.compilers>
- Keywords: C, code, optimize, question, comment
- Sender: compilers-sender@iecc.cambridge.ma.us
- Lines: 40
-
- 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:
-
- (*case_fun[switch_val])();
-
- after setting the pointers as:
-
- case_fun[0] = &case0;
- case_fun[10] = &case10;
- case_fun[31] = &case31;
- .
- .
- .
- etc.
-
- 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
- speed?
-
- Thanks,
-
- Ray
- [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]
- --
- Send compilers articles to compilers@iecc.cambridge.ma.us or
- {ima | spdcc | world}!iecc!compilers. Meta-mail to compilers-request.
-