Why Switch/Case and Not If/Else If

Why Switch/Case and not If/Else If?

Summarising my initial post and comments - there are several advantages of switch statement over if/else statement:

  1. Cleaner code. Code with multiple chained if/else if ... looks messy and is difficult to maintain - switch gives cleaner structure.

  2. Performance. For dense case values compiler generates jump table, for sparse - binary search or series of if/else, so in worst case switch is as fast as if/else, but typically faster. Although some compilers can similarly optimise if/else.

  3. Test order doesn't matter. To speed up series of if/else tests one needs to put more likely cases first. With switch/case programmer doesn't need to think about this.

  4. Default can be anywhere. With if/else default case must be at the very end - after last else. In switch - default can be anywhere, wherever programmer finds it more appropriate.

  5. Common code. If you need to execute common code for several cases, you may omit break and the execution will "fall through" - something you cannot achieve with if/else. (There is a good practice to place a special comment /* FALLTHROUGH */ for such cases - lint recognises it and doesn't complain, without this comment it does complain as it is common error to forgot break).

Thanks to all commenters.

Is else if faster than switch() case ?

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.

Why the switch statement and not if-else?

A switch construct is more easily translated into a jump (or branch) table. This can make switch statements much more efficient than if-else when the case labels are close together. The idea is to place a bunch of jump instructions sequentially in memory and then add the value to the program counter. This replaces a sequence of comparison instructions with an add operation.

Below are some extremely simplified psuedo-assembly examples. First, the if-else version:

    // C version
if (1 == value)
function1();
else if (2 == value)
function2();
else if (3 == value)
function3();

// assembly version
compare value, 1
jump if zero label1
compare value, 2
jump if zero label2
compare value, 3
jump if zero label3
label1:
call function1
label2:
call function2
label3:
call function3

Next is the switch version:

    // C version
switch (value) {
case 1: function1(); break;
case 2: function2(); break;
case 3: function3(); break;
}

// assembly version
add program_counter, value
call function1
call function2
call function3

You can see that the resulting assembly code is much more compact. Note that the value would need to be transformed in some way to handle other values than 1, 2 and 3. However, this should illustrate the concept.

When to use If-else if-else over switch statements and vice versa

As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.

As an example, if you were doing:

int value = // some value
if (value == 1) {
doThis();
} else if (value == 2) {
doThat();
} else {
doTheOther();
}

This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.

Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.

Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)

Is there any reason to use switch statement instead of strings of if and elseif?

They may well compile to the same code. But the intent is not necessarily to provide better compiled code so much as it is to provide better source code.

You can do while or for loops with if and goto as well but that doesn't make while and for useless. Would you rather have:

for (i = 0; i < 10; i++)
doSomethingWith (i);

or:

    i = 0;
loop12:
if (! (i < 10))
goto skip12
doSomethingWith (i);
i++;
goto loop12
skip12:

Case vs If Else If: Which is more efficient?

It seems that the compiler is better in optimizing a switch-statement than an if-statement.

The compiler doesn't know if the order of evaluating the if-statements is important to you, and can't perform any optimizations there. You could be calling methods in the if-statements, influencing variables. With the switch-statement it knows that all clauses can be evaluated at the same time and can put them in whatever order is most efficient.

Here's a small comparison:

http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx

Which is Faster and better, Switch Case or if else if?

Your first example is simply wrong. You need elseif instead of just else.

If you use if..elseif... or switch is mainly a matter of preference. The performance is the same.

However, if all your conditions are of the type x == value with x being the same in every condition, switch usually makes sense. I'd also only use switch if there are more than e.g. two conditions.

A case where switch actually gives you a performance advantage is if the variable part is a function call:

switch(some_func()) {
case 1: ... break;
case 2: ... break;
}

Then some_func() is only called once while with

if(some_func() == 1) {}
elseif(some_func() == 2) {}

it would be called twice - including possible side-effects of the function call happening twice. However, you could always use $res = some_func(); and then use $res in your if conditions - so you can avoid this problem alltogether.

A case where you cannot use switch at all is when you have more complex conditions - switch only works for x == y with y being a constant value.

Advantage of switch over if-else statement

Use switch.

In the worst case the compiler will generate the same code as a if-else chain, so you don't lose anything. If in doubt put the most common cases first into the switch statement.

In the best case the optimizer may find a better way to generate the code. Common things a compiler does is to build a binary decision tree (saves compares and jumps in the average case) or simply build a jump-table (works without compares at all).



Related Topics



Leave a reply



Submit