home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #27 / NN_1992_27.iso / spool / comp / compiler / 1934 < prev    next >
Encoding:
Text File  |  1992-11-22  |  2.0 KB  |  54 lines

  1. Newsgroups: comp.compilers
  2. Path: sparky!uunet!world!iecc!compilers-sender
  3. From: raymond@harp.ecn.purdue.edu (Ray Kamin)
  4. Subject: optimizing case-statement execution
  5. Reply-To: raymond@harp.ecn.purdue.edu (Ray Kamin)
  6. Organization: Purdue University Engineering Computer Network
  7. Date: Sun, 22 Nov 1992 19:18:31 GMT
  8. Approved: compilers@iecc.cambridge.ma.us
  9. Message-ID: <92-11-126@comp.compilers>
  10. Keywords: C, code, optimize, question, comment
  11. Sender: compilers-sender@iecc.cambridge.ma.us
  12. Lines: 40
  13.  
  14. How do compilers (in my case gcc v2.2.2) handle large switch statements?
  15. I have a 120 way switch in my code.  I looked at the sparc assembly code
  16. produced by gcc and it apparently doesn't use any sort of jump table, but
  17. merely does sequential comparisons and branches.
  18.  
  19. With this in mind, I rewrote the code with each 'case' statement as a
  20. separate function.  I then created a pseudo jump table with function
  21. pointers to each of these functions.  That is, I call:
  22.  
  23. (*case_fun[switch_val])();
  24.  
  25. after setting the pointers as:
  26.  
  27.   case_fun[0] = &case0;
  28.   case_fun[10] = &case10;
  29.   case_fun[31] = &case31;
  30.    .
  31.    .
  32.    .
  33.   etc.
  34.  
  35. The code is working correctly, however, it is not any faster at all.  Does
  36. anyone have any insight into this, or how this should be written for
  37. speed?
  38.  
  39. Thanks,
  40.  
  41. Ray
  42. [There are three general ways to generate code for a switch: a jump table,
  43. which is appropriate if the cases are numerically close to each other, a
  44. binary-compare and branch tree if the set of cases is large and sparse, and
  45. a sequential compare and branch otherwise.  I'd expect that the overhead of
  46. a procedure call would swamp any gain in indirecting through a table, if the
  47. time spent in this part of your program is in fact large enough to make any
  48. difference.  If you really need speed, GCC lets you create arrays of labels
  49. to use like a Fortran computed GOTO, but that is of course ugly and not very
  50. portable. -John]
  51. -- 
  52. Send compilers articles to compilers@iecc.cambridge.ma.us or
  53. {ima | spdcc | world}!iecc!compilers.  Meta-mail to compilers-request.
  54.