在返回值的函数中使用 else if/if 在性能上有什么不同吗?我的意思是,如果函数已经返回,它不会执行下一个 if,这就是 else if 的目的,对吧?我写了一个小代码片段来说明这一点
#include <iostream>
bool foo(int x)
{
if (x == 3) return 1;
else if (x == 4) return 1; //using only if here has the performance of else if?
return 0;
}
int main()
{
int x = 4;
std::cout << foo(x);
std::cin.get();
return 0;
}
最佳答案
应该都是一样的,检查性能更好的一种方法是比较你的汇编代码,你可以使用像 godbolt.org 这样的工具,通常生成更少指令的代码执行得更快。
顺便说一下,如果你在其他两种情况之前比较“return 0”会更好,因为几乎 100% 的时间你的输入参数不是 3 或 4,
if (x != 3) return 0;
return 1;
比
好多了if (x == 3) return 1;
return 0;
关于c++ - 性能:else if vs if 在已经返回的函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49713340/