Reputation: 131799
I got a function pointer for a deleter, but most of the time, the deleter is not gonna be needed, only when I maintain an internal copy of something. Currently I do that with a noop deleter function:
class MyClass{
public:
// bind object
template<class Type>
void Bind(Type* obj){
Cleanup();
object_ = obj;
}
// bind object with internal copy
template<class Type>
void Bind(Type obj){
Cleanup();
object_ = new Type(obj);
deleter = &Deleter<Type>;
}
private:
template<class Type>
static void Deleter(void* obj_ptr){
Type* obj = static_cast<Type*>(obj_ptr);
delete obj;
}
static void NoopDeleter(void* unused){
}
void Cleanup(){
(*deleter_)(object_);
object_ = 0;
deleter_ = &NoopDeleter;
}
typedef void (*DeleterFunc)(void*);
void* object_;
DeleterFunc deleter_;
};
Now the obvious other choice would be to set it to 0
when not needed, and check in the Cleanup
function with if(deleter_ != 0) (*deleter_)(object_)
.
Now during the coding, it just came to my mind "Hm, which version would be faster?", so it's more of a personal interest rather than optimization. Sorry if the question sounds kinda stupid, but it kinda bugs me and I really want to know. Thanks for any answers in advance!
Upvotes: 3
Views: 1128
Reputation: 106106
A variable comparison to 0 will be faster than a function call (typically a single cycle), particularly given the variable has to be loaded into a register to make the function call anyway. Overheads include adjusting the stack, pushing object_
and the return address, calling into the function....
Upvotes: 1
Reputation: 1716
Function call has to setup a stack frame. All the if-statement has to do is execute a single machine instruction. Maybe two, depending on the rchitecture of the machine.
Upvotes: 3