If-statement vs function pointer

Davorin picture Davorin · Jan 3, 2014 · Viewed 7.8k times · Source

The goal is to change the behaviour in an event loop, depending on whether a checkbox is toggled on or off. The simplest way, that I can think of, is just to test the checkbox state each time the loop is run.

// if-statement

void action() { /* ... */ }


void someLoop() {

  if (checkboxTrue) {
    action();
  }
  // ... other stuff

}

Would the code be more performant and cleaner or in any other way better, if a function pointer was being used? Like this:

// function pointer

void action() { /* ... */ }
void empty() {}
void (*actionPtr)();


void checkboxChanged(int val) {

  if (val == 1)
    actionPtr = &realAction;
  else
    actionPtr = ∅

}

void someLoop() {

  (*actionPtr)();
  // ... other stuff

}

Answer

  1. One indirect function call is more expensive than one if condition.

  2. Several if conditions are more expensive than an indirect function call.

  3. Worrying about speed at this point is pointless:
    You are waiting on the latency of the user, and you are handling stuff he can look at (i. e. there won't be huge amounts of checkboxes). Optimizing code that is executed less than a million times per second on a detailed level like this is absolutely pointless.

So, my advise is: stop worrying about the cost of an if or function call while you are programming a user interface. Only think about such stuff inside your time consuming algorithms.

However, if you find that you are indeed using complex if/else ladders and/or switch statements inside your inner loop, you might optimize by replacing those with indirect function calls.


Edit:
You say that you have 600 checks per second. Assuming you have only one if case to handle (the situation where the if is faster), you "save" roughly 6 microseconds per second by not using function pointer indirection, that's 0.0006% of the runtime. Definitely not worth the effort...