使用bool并稍后返回或调用函数并立即返回是否更快? C ++

时间:2017-05-10 08:28:12

标签: c++

我有一个问题,理论上哪种方法运行起来会更快?我有一个CPU密集型功能,在某些条件下无法运行。基本上我要问的是,在同一个函数中复制多次使用多个参数的调用代码是否更快,或者仅使用bool使组件更小更快?感谢

bool ShouldNotDoExpensiveFunction = false;

if (!somefunction())
{
    ShouldNotDoExpensiveFunction = true;
}
else if (!somefunction2())
{
    ShouldNotDoExpensiveFunction = true;
}
else if (!somefunction3())
{
    ShouldNotDoExpensiveFunction = true;
}
else if (!somefunction4())
{
    ShouldNotDoExpensiveFunction = true;
}

if (!ShouldNotDoExpensiveFunction)
{
    return RunExpensiveFunction(1, 2, 3, 4, 5, 6, 7, 8, 9);
}
else
{
     return RunInexpensiveFunction(1, 2);
}

or


if (!somefunction())
{
    return RunInexpensiveFunction(1, 2);
}
else if (!somefunction2())
{
    return RunInexpensiveFunction(1, 2);
}
else if (!somefunction3())
{
    return RunInexpensiveFunction(1, 2);
}
else if (!somefunction4())
{
    return RunInexpensiveFunction(1, 2);
}
else
{
    return RunExpensiveFunction(1, 2, 3, 4, 5, 6, 7, 8, 9);
}

1 个答案:

答案 0 :(得分:0)

两个片段的性能可能相当。由于您的功能非常耗费CPU,因此这些方法之间的潜在边际差异很可能是微不足道的。编译器甚至可以为每个组件生成相同的程序集。

前者优于后者,不是出于性能原因,而是因为你避免重复参数,从而使代码变得不那么脆弱。

有一种更好的方法,不需要任何重复:

return somefunction() && somefunction2() && somefunction3() && somefunction4()
    ? RunExpensiveFunction(1, 2, 3, 4, 5, 6, 7, 8, 9)
    : RunInexpensiveFunction(1, 2);