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

Kamil Skalski nazgul at omega.pl
Sat Mar 20 04:58:46 EST 2004


Saturday 20 of March 2004 10:49, Richard Torkar wrote:
> On Sat, 2004-03-20 at 03:17 +0000, Marcus wrote:
> > In one of my projects, I have a large number of cases where I make
> > three-way decisions based on a string comparison. I wrote a short test
> > program with a three-way decision using nested if-statements and a switch
> > statement to see which was more efficient. I did have to use a large
> > number of iterations in a loop to get reliable timing numbers, but once I
> > did, I found that using this if-statement in a loop took about 112 ms:
> >
> >             if ( list[i] == "Apple" )
> >                 x = 1;
> >             else if ( list[i] == "Banana" )
> >                 x = 2;
> >             else
> >                 x = 3;
> >
> > whereas this switch took about 889 ms:
> >
> >             switch ( list[i] )
> >             {
> >                 case "Apple": x = 1; break;
> >                 case "Banana": x = 2; break;
> >                 default: x = 3; break;
> >             }
>
> 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.

It is also more readable IMHO. And it looks also like (SML/OCaml/Nemerle) 
matching :D
  def x =
     match ( list[i] )
      {
         | "Apple" => 1
         | "Banana" => 2
         | _ => 3
     };

(additionally, C# / Nemerle compilers do some nice tricks with code like 
above, tree automata, binary search and others are made).

Kamil Skalski



More information about the Mono-devel-list mailing list