[MUD-Dev] Re: Question on c++ switch optimization, and parsers in general.

Richard Woolcock KaVir at dial.pipex.com
Tue Feb 9 02:16:44 CET 1999


Ben Greear wrote:
> 
> Well, after the 400th person said my parse engine was an insult to
> hackers everywhere (I was the first of those 400!!), I am re-writing it.
> 
> Basically, I'll have a bunch of classes hashed into an array
> that will contain the keywords mapped to an enum.
> 
> Now, I get the enum, and then I need to call the various commands
> that the enum maps to.
> 
> Currently, I'm using a huge (~400 cases) switch statement.
> 
> So, the question is:  Is that efficient?  Does the compiler
> generate code that does better than a linear search down the
> case statements?  If not, I can manually hack a sort of n-ary
> tree performance into it, but I'd wrather not if I can help it.

I don't know about C++, but I can speak for C.

I believe that switch statements are compiled down to the equivilent
of if statements, ie:

   switch ( x )
   {
      case 1: ...
      case 2: ...
      case 3: ...
      default: ...
   }

Is no more efficient than:

   if      ( x == 1 ) ...
   else if ( x == 2 ) ...
   else if ( x == 3 ) ...
   else ...

So basically, no, it's no better than a linear search.  Not that it 
really matters, unless you have thousands of commands.  I prefer the
diku-style array of commands, but you'd have to go through that in
a linear fashion too (you could do a binary search through it, but
that might result in annoying things like typing 's' resulting in
'sit' rather than 'south').  Still, it's nicer to look at.

Some more modern compilers may treat switch statements better than
the ones I'm used to - if so, I'd appreciate it if someone told me :)

KaVir.




More information about the mud-dev-archive mailing list