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

Ivan Prodanov picture Ivan Prodanov · Apr 20, 2009 · Viewed 383.6k times · Source

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 similar structure (many, many "else if" statements). Should I turn them into switches?

Answer

Guffa picture Guffa · Apr 20, 2009

For just a few items, the difference is small. If you have many items you should definitely use a switch.

If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.