tags:

views:

3878

answers:

14

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?

+3  A: 

Shouldn't be hard to test, create a function that switches or ifelse's between 5 numbers, throw a rand(1,5) into that function and loop that a few times while timing it.

Ólafur Waage
+2  A: 

Technically, they produce the exact same result so they should be optimizable in pretty much the same way. However, there are more chances that the compiler will optimize the switch case with a jump table than the ifs.

I'm talking about the general case here. For 5 entries, the average number of tests performed for the ifs should be less than 2.5, assuming you order the conditions by frequency. Hardly a bottleneck to write home about unless in a very tight loop.

jfclavette
+4  A: 

I'd say the switch is the way to go, it is both faster and better practise.

There are various links such as (http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx) that show benchmark tests comparing the two.

sbohan
+3  A: 

Switch is generally faster than a long list of ifs because the compiler can generate a jump table. The longer the list, the better a switch statement is over a series of if statements.

Steven
Noet that the jump-table only applies (IIRC) for contiguous values. It is not uncommon for the compiler to emit a mix of jump-tables and breq for complex non-contiguous options.
Marc Gravell
+2  A: 

Believing this performance evaluation, the switch case is faster.

This is the conclusion:

The results show that the switch statement is faster to execute than the if-else-if ladder. This is due to the compiler's ability to optimise the switch statement. In the case of the if-else-if ladder, the code must process each if statement in the order determined by the programmer. However, because each case within a switch statement does not rely on earlier cases, the compiler is able to re-order the testing in such a way as to provide the fastest execution.

Michael Barth
+2  A: 

switch usually gets translated into a lookup table by the compiler, if possible. So lookup of an arbitrary case is O(1), instead of actually doing a few case comparisons before finding the one you want.

So in many cases an if/else if chain will be slower. Depending on the frequency with which your cases are being hit that may make no difference, though.

Joey
+39  A: 

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.

Guffa
True, but with an if-else-if chain you can order the conditions based on how likely they are to be true.
Dave Van den Eynde
Yes, but the first 4-5 cases has to catch very close to 100% of the occurances to make up for the slower ones.
Guffa
Shouldn't most modern compilers optimize deep if/else if/else if/else if decision points as a switch/jump table? Which is to say; this shouldn't matter, the compiler's going to optimize it, why not just write the most readable code?
Dean J
@Dean J: Yes, generally you should write the most readable code even if the performance differs somewhat. If you need to optimise the code it may still make a difference. For the compiler to optimise the code the way that you describe, it has to have more knowledge about the value, i.e. knowing if reading the value multiple times has any side effects, as changing the code to a switch will only read the value once.
Guffa
+1  A: 

Short answer: Switch statement is quicker

The if statement you need two comparisons (when running your example code) on average to get to the correct clause.

The switch statement the average number of comparisons will be one regardless of how many different cases you have. The compiler/VM will have made a "lookup table" of possible options at compile time.

Can virtual machines optimize the if statement in a similar way if you run this code often?

AnnaR
+3  A: 

As ever - test and find out!

Visage
+4  A: 

Another thing to consider: is this really the bottleneck of your application? There are extremely rare cases when optimization of this sort is really required. Most of the time you can get way better speedups by rethinking your algorithms and data structures.

Vilx-
+2  A: 

Far more important than the performance benefits of switch (which are relatively slight, but worth noting) are the readability issues.

I for one find a switch statement extremely clear in intent and pure whitespace, compared to chains of ifs.

annakata
+21  A: 

Why do you care?

99.99% of the time, you shouldn't care.

These sorts of micro-optimizations are unlikely to affect the performance of your code.

Also, if you NEEDED to care, then you should be doing performance profiling on your code. In which case finding out the performance difference between a switch case and an if-else block would be trivial.

Edit: For clarity's sake: implement whichever design is clearer and more maintainable. Generally when faced with a huge switch-case or if-else block the solution is to use polymorphism. Find the behavior that's changing and encapsulate it. I've had to deal with huge, ugly switch case code like this before and generally it's not that difficult to simplify. But oh so satisfying.

Wedge
I think 100% of the time, you shouldn't care.
Naveen
I absolutely don't agree. You definitely should always care, not so much because of performance, but this also affects code readability and maintainability. And, as mentioned by others, you might well think about a better utilization of polymorphism.
0xA3
Oh, I agree that you should always care about readability and maintainability. The proper way to rewrite a huge switch/case block is probably polymorphism (which, incidentally, is probably slightly slower, but you shouldn't care). Macro-optimization (good design) is always better than micro-optimization (faster statements).
Wedge
Agreed - if you have to care about this level of optimisation then you probably shouldn't be using a CLR-based managed language in the first place.
GrahamS
@GrahamS, That's a bit of a misnoma. virtual machines can be every bit as fast as "real" ones... not the least because the runtime can optimize much better than a compiler, because it can measure what actually needs optimizing. PS: My java solution to the Maze of Bolton takes 0.03375655565 seconds. The published winning C# solution takes 0.166 seconds, with C++ in second place at 429.46 seconds to find the incorrect answer. And CLR is inherently slow? Hmmm... I don't think so Tim ;-)
corlettk
A: 

Since the switch statement expresses the same intent as your if / else chain but in a more restricted, formal manner, your first guess should be that the compiler will be able to optimize it better, since it can draw more conclusions about the conditions placed on your code (i.e. only one state can possibly be true, the value being compared is a primitive type, etc.) This is a pretty safe general truth when you are comparing two similar language structures for runtime performance.

mquander
+1  A: 

I'm not sure, but i believe the speed of one or the other changes depending on the programming language you're using.

I usually prefer to use switch. That way the code is simplear to read.