我正在寻找优化我的更新循环,并解决了这个代码:
// Define two lambda functions
auto iftrue = [](int x, int y) -> int {
return x;
};
auto iffalse = [](int x, int y) -> int {
return y;
};
// Define a pointer to a function that takes two integers and returns an integer
typedef int (*FunctionPointer)(int, int);
FunctionPointer ptr = nullptr;
void SetFalse()
{
ptr = iffalse;
}
void SetTrue()
{
ptr = iftrue;
}
int main() {
int a = 5, b = 3;
SetTrue();
// Use the second lambda function
int result = ptr(a, b);
std::cout << "Result: " << result << std::endl;
SetFalse();
// Use the second lambda function
result = ptr(a, b);
std::cout << "Result: " << result << std::endl;
return 0;
}
我突然意识到,这不是总是比 if 语句运行得更好吗?
我检查了速度,然后... https://onlinegdb.com/mCZc6Eb7Z
功能似乎更快了。难道不应该尽可能将所有内容都改为函数指针吗?
非常简短的答案是,当处理代码时,编译器会尝试预测
if
语句的结果以进行优化。 但是,如果预测错误,CPU 的成本可能会非常高。
对于函数指针,你去掉了执行路径的条件部分,所以上面的情况不会发生,并且在某些情况下代码会运行得更快。
所以最终,你的问题的答案是分支预测。