Avoiding Branch Operations in Switch Statements

337 Views Asked by At

Instead of a switch statement running iterating through branch after branch, is there away to make assembly look up a list in an array for a goto statement? Or is this usually optimized in the compiler?

Such an optimization would help immensely for large switch statements with constant values.

Ex:

switch(test) {
case 1:
// Do something
break;
case 2:
// Do something
break;
}

"Optimized":

action_link[] = {action_1, action_2};
goto action_link[test];

action_1:
// Do Something
action_2:
// Do Something
2

There are 2 best solutions below

0
On

The compiler will make this decision for you, based on your optimisation settings and its heuristics about what might make a good jump table.

In many simple situations, the compiler might decide that a naive test-and-jump chain would be faster or smaller than the equivalent jump table.

0
On

That is indeed what you should expect from a decent compiler. In fact, the limitations of the switch statement were based on making it easy to translate to a "jump table" instead of multiple branches. Back at the dawn of time, FORTRAN had the "computed GOTO" for the same reason.