[Mono-devel-list] mcs code for switches on strings

Jonathan Pryor jonpryor at vt.edu
Sat Mar 20 07:44:06 EST 2004


Below...

On Sat, 2004-03-20 at 04:49, Richard Torkar wrote:
> On Sat, 2004-03-20 at 03:17 +0000, Marcus wrote:
<snip/>
> Hmm, is it just me or isn't switch/case supposed to execute faster when
> comparing several strings like above? I learnt that many years ago, thus
> I consequently use switch/case in stead of nested if-statements if it
> looks like the above.
> 
> Is this not true anymore as a general rule?

Nothing is true as a general rule.  Everything has an exception. :-)

Except the general rule of "test first, optimize later."  Except when
you're creating the design, in which case you need to make sure the
design will meet your performance requirements.  Guess there's an
exception here to...

There are numerous ways to implement the switch statement for strings,
from using an internal array of strings and binary-searching the array,
using the array to get the code offset, then jumping, to using a
Dictionary of strings to lookup the jump point.  Many techniques are
possible.

The issue is that all of those techniques have some amount of overhead
associated with them.  So switching on 2 strings + default case is not
enough strings lookups to overcome the overhead of many implementation
techniques, at least in this case.  I'm not sure what the break-even
point is, and that would depend upon the length of those strings as well
as the number of strings in the switch.

Now, it might be possible to add intelligence to the compiler so that it
knows what the break-even point is, and have it emit an "if" tree if
some threshold isn't reached.  This might not be possible, though,
especially if you have case statements that don't end in "break", but
instead end with "goto case FOO".

In any event, this would be something to look into implementing. :-)

 - Jon





More information about the Mono-devel-list mailing list