I have an array of call backs like this void (*callbacks[n])(void* sender) and I’m wondering which one of these codes will preform faster :
//Method A
void nullcallback(void* sender){};
void callbacka(void* sender)
{
printf("Hello ");
}
void callbackb(void* sender)
{
printf("world\n");
}
int main()
{
void (*callbacks[5])(void* sender);
unsigned i;
for (i=0;i<5;++i)
callbacks[i] = nullcallback;
callbacks[2] = callbacka;
callbacks[4] = callbackb;
for (i=0;i<5;++i)
callbacks[i](NULL);
};
or
//Method B
void callbacka(void* sender)
{
printf("Hello ");
}
void callbackb(void* sender)
{
printf("world\n");
}
int main()
{
void (*callbacks[5])(void* sender);
unsigned i;
for (i=0;i<5;++i)
callbacks[i] = NULL;
callbacks[2] = callbacka;
callbacks[4] = callbackb;
for (i=0;i<5;++i)
if (callbacks[i])
callbacks[i](NULL);
};
some conditions:
- Does it matter if I know most of my callbacks are valid or not?
- Does it make a difference if I’m compiling my code using C or C++ compiler?
- Does the target platform (windows, linux, mac, iOS, android) change any thing in the results? (the whole reason for this callback array is to manage callbacks in a game)
This totally depends on your actual situation. If possible I would prefer methode A, because it is simply easier to read and produce cleaner code, in particular if your function has a return value:
Of course methode A becomes tedouis when you have not only one function signature but let’s say 100 different signature. And for each you have to write a null function.
For the performance consideration it depends if the nullcallback() is a rare case or not. If it is rare, methode A is obviously faster. If not methode B could be slightly faster, but that depends on many factors: which platform you use, how many arguments your functions have, etc. But in any case if your callbacks are doing “real work”, ie. not only some simple calculations, it shouldn’t matter at all.
Where your methode B could really be faster is when you not only call the callback for one sender but for very many:
Here the entire loop is skipped when there is no valid callback. This tweak can also be done with methode A if the nullcallback() address is known, ie. not defined in some module only.