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

Marcus mathpup at mylinuxisp.com
Fri Mar 19 22:23:45 EST 2004


Test case:

using System;


public class Branch
{
    public static void Main()
    {
        const int size = 1000000;
        string[] list = new string[size];
        int x = 0;


        // Fill the array with a sample of the three different strings
        // (This is intentionally not a uniform distribution

        for ( int i = 0; i < size; i++ )
        {
            if ( i % 5 == 0 )
                list[i] = "Apple";
            else if ( i % 11 == 0 )
                list[i] = "Banana";
            else
                list[i] = "Cherry";
        }

        DateTime startTime = DateTime.Now;

        for ( int i = 0; i < size-1; i++ )
        {
            if ( list[i] == "Apple" )
                x = 1;
            else if ( list[i] == "Banana" )
                x = 2;
            else
                x = 3;
        }

        TimeSpan ifTime = DateTime.Now - startTime;
        startTime = DateTime.Now;

        for ( int i = 0; i < size-1; i++ )
        {
            switch ( list[i] )
            {
                case "Apple": x = 1; break;
                case "Banana": x = 2; break;
                default: x = 3; break;
            }
        }

        TimeSpan switchTime = DateTime.Now - startTime;

        Console.WriteLine( x );

        Console.WriteLine( "Time using if-statement: {0}", 
ifTime.TotalMilliseconds );
        Console.WriteLine( "Time using switch-statement: {0}", 
switchTime.TotalMilliseconds );
    }
}



More information about the Mono-devel-list mailing list