noop 函数调用和 if 语句哪个更快?
我有一个删除器的函数指针,但大多数时候,只有当我维护某些内容的内部副本时才需要删除器。目前我使用 noop 删除器函数来做到这一点:
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_;
};
现在明显的其他选择是在不需要时将其设置为 0
,并使用 签入
.Cleanup
函数if(deleter_ != 0) (*deleter_)(object_)
现在在编码过程中,我突然想到“嗯,哪个版本会更快?”,所以这更多是个人兴趣而不是优化。抱歉,如果这个问题听起来有点愚蠢,但这有点困扰我,我真的很想知道。感谢您提前的任何答复!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
函数调用必须设置堆栈帧。所有 if 语句所要做的就是执行一条机器指令。也许两个,具体取决于机器的结构。
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.
与 0 进行比较的变量将比函数调用(通常是单个周期)更快,特别是考虑到无论如何都必须将变量加载到寄存器中才能进行函数调用。开销包括调整堆栈、推送
object_
和返回地址、调用函数......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....