3

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!

Xeo
  • 129,499
  • 52
  • 291
  • 397
  • 3
    The answer to any question "which is faster" is to measure it. There are so many variables that it's hard to draw general conclusions. Especially when testing both possibilities is actually easier than asking the question on a forum! – Mark Ransom Mar 22 '11 at 03:29

2 Answers2

3

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.

Vagrant
  • 1,696
  • 12
  • 19
  • And fetch the function pointer, and deal with the argument, and return from the no-op function... – Jonathan Leffler Mar 22 '11 at 03:28
  • And possibly page faulting the memory with the RET instruction on it. :) – Vagrant Mar 22 '11 at 03:50
  • How much stackframe do you need in an empty function? None? The if-statement will have to deal with the pointer as well, so I don't think you save much there. @Xeo: Just do the measure, and tell us if the difference is 1 or 2 nanoseconds! – Bo Persson Mar 22 '11 at 08:05
1

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....

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252