Search code examples
cperformanceif-statementswitch-statementprocessing-efficiency

Small switch statement vs small if chain?


In the realm of performance which is consider more efficient?:

A small switch statement consisting of under 3 cases/below 3 cases? Or A small if chain consisting of under 3 conditions/below 3 conditions?

For example:

int x = 1;
switch (x) {
    case 1:
        //....do something
    case 2:
        //....do something
    case 3:
        //....do something
}

Or

int x = 1:
if (x == 1) {
    //....do something
}
else if (x == 2) {
    //....do something
}
else if (x == 3) {
    //....do something
}

Are both considered equally efficient? Or does one dominate the other via speed?


Solution

  • In theory, the switch statement is usually faster than an if/else ladder because a switch statement compiles to a jumptable when remotely possible to do so. My understanding is modern optimizers can do as well for that if-then-else ladder so in practice it won't be faster.

    In the worst case, the switch statement will not be slower, so if in doubt, write the switch statement. Besides, it's easier to read and that's almost always worth it.