is "else if" faster than "switch() case" ?

Posted by John on Stack Overflow See other posts from Stack Overflow or by John
Published on 2009-04-20T11:07:15Z Indexed on 2010/04/04 12:53 UTC
Read the original article Hit count: 121

Filed under:
|
|

Hello,

I'm an ex Pascal guy,currently learning C#. My question is the following:

Is the code below faster than making a switch?

    int a = 5;

    if (a == 1)
    {
        ....
    }
    else if(a == 2)
    {
        ....
    }
    else if(a == 3)
    {
        ....
    }
    else if(a == 4)
    {
        ....
    }
    else
        ....

And the switch:

int a = 5;

switch(a)
{
    case 1:
        ...
        break;

    case 2:
        ...
        break;

    case 3:
        ...
        break;

    case 4:
        ...
        break;

    default:
        ...
        break;


}

Which one is faster?

I'm asking ,because my program has a similiar structure(many,many "else if" statements). Should I turn them into switches?

© Stack Overflow or respective owner

Related posts about c#

Related posts about native