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

Marcus mathpup at mylinuxisp.com
Fri Mar 19 22:17:03 EST 2004


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;
            }

When I looked at the CIL generated, I noticed that mcs was generating calls to 
op_Equality for the string comparisons in the if-statement version, whereas 
in the switch version, mcs generated calls to IsInterned() followed by a 
branch-not-equal comparison of the string to the constant.

What is the reasoning here for emitting the different kind of code, and is it 
a valid one?





More information about the Mono-devel-list mailing list