多个 If 语句与使用逻辑运算符评估条件的单个语句

WAR*_*ead 1 c++ performance if-statement logical-operators

我正在编写一个函数,在实际执行其任务之前检查几个条件。这是通过许多if语句完成的。像这样:

bool foo()
{
    if(invalid())
        return false;
    if(dont_execute())
        return false;
    // .. etc
    // Actual execution here
    return true;
}
Run Code Online (Sandbox Code Playgroud)

在此函数中,将多个条件更改为:

bool foo()
{
    if(invalid() || dont_execute() /* || .. etc */)
        return false;
    // Actual execution here
    return true;
}
Run Code Online (Sandbox Code Playgroud)

我觉得第一种风格更具可读性。我想知道的是,使用多个 if 语句而不是组合使用逻辑运算符是否对性能有任何影响。

Tim*_*imo 5

不,没有性能影响。如果我们比较两个函数的汇编,我们可以看到这两个函数是相同的。

例子:

bool f1();
bool f2();

bool combined()
{
    if (f1() || f2())
        return false;

    return true;
}

bool separate()
{
    if (f1())
        return false;

    if (f2())
        return false;

    return true;
}
Run Code Online (Sandbox Code Playgroud)

这里是大会:

combined():
        sub     rsp, 8
        call    f1()
        mov     r8d, eax
        xor     eax, eax
        test    r8b, r8b
        jne     .L1
        call    f2()
        xor     eax, 1
.L1:
        add     rsp, 8
        ret

separate():
        sub     rsp, 8
        call    f1()
        mov     r8d, eax
        xor     eax, eax
        test    r8b, r8b
        jne     .L7
        call    f2()
        xor     eax, 1
.L7:
        add     rsp, 8
        ret
Run Code Online (Sandbox Code Playgroud)