Alex Rivera | Logout

Performance of array of functions over if and switch statements

Asked 2011-04-07T13:54:58.730
19

I am writing a very performance critical part of the code and I had this crazy idea about substituting case statements (or if statements) with array of function pointers.

Let me demonstrate; here goes the normal version:

while(statement)
{
    /* 'option' changes on every iteration */

    switch(option)
    {
        case 0: /* simple task */ break;
        case 1: /* simple task */ break;
        case 2: /* simple task */ break;
        case 3: /* simple task */ break;
    }
}

And here is the "callback function" version:

void task0(void) {
    /* simple task */
}

void task1(void) {
    /* simple task */
}

void task2(void) {
    /* simple task */
}

void task3(void) {
    /* simple task */
}

void (*task[4]) (void);

task[0] = task0;
task[1] = task1;
task[2] = task2;
task[3] = task3;

while(statement)
{
    /* 'option' changes on every iteration */

    /* and now we call the function with 'case' number */
    (*task[option]) ();
}

So which version will be faster? Is the overhead of the function call eliminating speed benefit over normal switch (or if) statement?

Ofcourse the latter version is not so readable but I am looking for all the speed I can get.

I am about to benchmark this when I get things set up but if someone has an answer already, I wont bother.

Edit
Report

2 Answers

3

The switch statement should be compiled into a branch table, which is essentially the same thing as your array of functions, if your compiler has at least basic optimization capability.

answered 2011-04-07T14:17:23.560
2

First, I would randomly-pause it a few times, to make certain enough time is spent in this dispatching to even bother optimizing it.

Second, if it is, since each branch spends very few cycles, you want a jump table to get to the desired branch. The reason switch statements exist is to suggest to the compiler that it can generate one if the switch values are compact.

How long is the list of switch values? If it's short, the if-ladder could still be faster, especially if you put the most frequently used codes at the top. An alternative to an if-ladder (that I've never actually seen anyone use) is an if-tree, the code equivalent of a binary tree.

You probably don't want an array of function pointers. Yes, it's an array reference to get the function pointer, but there's several instructions' overhead in calling a function, and it sounds like that could overwhelm the small amount being done inside each function.

In any case, looking at the assembly language, or single-stepping at the instruction level, will give you a good idea how efficient it's being.

answered 2011-04-09T17:25:03.573

Your Answer