Fast switching..

janderson askme at me.com
Wed Jun 11 19:40:57 PDT 2008


Sean Kelly wrote:
> == Quote from Georg Wrede (georg at nospam.org)'s article
>> Regan Heath wrote:
>>> Hi all,
>>>
>>> I've been AWOL from this NG for a while but recently a friend of mine
>>> sent me a link to this:
>>> http://blogs.msdn.com/jomo_fisher/archive/2007/03/28/fast-switching-with-linq.aspx
>>>
>>> and my first thought was; can something similar (or even better) be done
>>> in D. :)
>>>
>>> I admit, I haven't even spent 5 mins thinking about how I might do it,
>>> but I've never been particularly good with the compile time features of
>>> D so I figured I'd post something here and see what the people who are
>>> good at it can come up with.
>>>
>>> So, consider this a little challenge .. it may turn out to be trivial,
>>> it might not, I have no idea.
>> A language that allows you to write switch statements with strings
>> should have this built-in. But that is actually a quality of
>> implementation issue, and therefore transparent to the spec.
>> In real life, if I were to tackle this and there were less than two
>> dozen words, I'd figure it out manually. This would also allow for
>> optimizations, like if I expect some of the words to occur more often
>> than others.
> 
> I've done this quite often with simple parsers:
> 
> switch( token[0] )
> {
> case 'o':
>     if( strcmp( token, "one" ) )
>         throw new ParseFailure();
>     // blah
>     break;
> case 't':
>     if( !strcmp( token, "two" ) )
>         // stuff for "two"
>     else if( !strcmp( token, "three" ) )
>         // stuff for "three"
>     break;
> }
> 
> It's easy enough to do it all with switch statements as well, but I
> like the insurance that checking the entire string provides.  It would
> be nice if DMD optimized string-based switch statements this way.
> I'll admit to being a bit old-school in this respect--I've never actually
> used string switch statements in D.
> 
> 
> Sean


I thought in a discussion earlier with Walter (a few years back) that 
DMD would generate a string hash and then jump to that hash when you use 
a string as the input.  In many cases the branching will be the 
expensive part so I guess a hash is pretty close to optimal performance 
for the general case.  Although with optimisation you can always make 
things run faster.

-Joel



More information about the Digitalmars-d mailing list