dea*_*sin 7 c++ optimization function-pointers inline
在我的jpg解码器中,我有一个带有if语句的循环,它将始终为true或始终为false,具体取决于图像.我可以创建两个单独的函数来避免if语句,但我好奇地想知道效率对效率的影响是使用函数指针而不是if语句.如果为true,它将指向内联函数,如果为false,则指向空内联函数.
class jpg{
private:
// emtpy function
void inline nothing();
// real function
void inline function();
// pointer to inline function
void (jpg::*functionptr)() = nullptr;
}
jpg::nothing(){}
main(){
functionptr = &jpg::nothing;
if(trueorfalse){
functionptr = &jpg::function;
}
while(kazillion){
(this->*functionptr)();
dootherstuff();
}
}
Run Code Online (Sandbox Code Playgroud)
这可能比if语句快吗? 我的猜测是否定的,因为内联将是无用的,因为编译器将不知道在编译时内联哪个函数并且函数指针地址解析比if语句慢.
我已经对我的程序进行了描述,而且当我运行程序时,我预期会出现明显的差异......我没有遇到明显的差异.所以我只是出于好奇而想知道.
小智 8
if语句很可能比调用函数更快,因为if只是一个短跳转而不是函数调用的开销.
这里已经讨论过:哪个更快?函数调用或条件if语句?
"inline"关键字只是提示编译器告诉它在组装时尝试将指令内联.如果使用指向内联的函数指针,则无论如何都不能使用内联优化:
阅读:内联函数是否有地址?
如果你觉得if语句的速度太慢了,你可以通过使用单独的while语句来完全消除它:
if (trueorfalse) {
while (kazillion) {
trueFunction();
dootherstuff();
}
} else {
while (kazillion) {
dootherstuff();
}
}
Run Code Online (Sandbox Code Playgroud)