[comp.lang.c] lookuptables vs switch

breck@star.ecs.umass.edu (Liam Breck) (11/18/90)

Hello World,

I need to use one value to get a string from a list of values and
strings about 30 elements long.  I can think of two ways of doing it:
using an array of structures and a loop to search the array for the
desired value or a switch statement with 30 case labels.  Which is
faster?  If I put the switch in its own function how much will that
slow things down?

thanx

Liam Breck

gwyn@smoke.brl.mil (Doug Gwyn) (11/18/90)

In article <1351@umvlsi.ecs.umass.edu> breck@star.ecs.umass.edu (Liam Breck) writes:
>Which is faster?

Generally the switch statement will be faster than a search loop.

>If I put the switch in its own function how much will that slow things down?

How could we possibly know -- you haven't said what system you're using.

bright@nazgul.UUCP (Walter Bright) (11/20/90)

In article <1351@umvlsi.ecs.umass.edu> breck@star.ecs.umass.edu (Liam Breck) writes:
/I need to use one value to get a string from a list of values and
/strings about 30 elements long.  I can think of two ways of doing it:
/using an array of structures and a loop to search the array for the
/desired value or a switch statement with 30 case labels.  Which is
/faster?  If I put the switch in its own function how much will that
/slow things down?

Your results will vary greatly depending on your target machine and the
compiler used. Your best bet is to try it both ways and time the results
for your configuration.

I'd suggest looking at the routines bsearch() to search a table and
strchr() which can also be used for that if the values are all < 256.