Which is most efficient: using a null object, or a branch on nullptr. Example in C++:
void (*callback)() = [](){}; // Could be a class member
void doDoStuff()
{
// Some code
callback(); // Always OK. Defaults to nop
// More code
}
vs
void (*callback)() = nullptr; // Could be a class member
void doDoStuff()
{
// Some code
if(callback != nullptr) // Check if we should do something or not
{callback();}
// More code
}
The null object will always do an indirect function call, assuming the compiler cannot inline it. Using a nullptr, will always do branch, and if there is something to do, it will also do an indirect function call.
Would replacing callback with a pointer to an abstract base class affect the decision?
What about the likelihood of callback set to something other than nullptr. I guess that if callback is most likely nullptr, then it is faster with the additional branch, right?