Search code examples
c++performanceif-statementlogical-operators

Multiple If statements versus single statement with conditions evaluated using logical operators


I am writing a function that checks several conditions before actually executing its task. This is done by a number of if statements. Like so:

bool foo()
{
    if(invalid())
        return false;
    if(dont_execute())
        return false;
    // .. etc
    // Actual execution here
    return true;
}

In this function is there any benefits by changing the multiple conditions to :

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

I feel that the first style is more readable. What I want to know is, if there is any performance impact in using multiple if statements rather than combining using logical operators.


Solution

  • No there is no performance impact. If we compare the assembly of both functions we can see that it is identical for both functions.

    Example:

    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;
    }
    

    And here the assembly:

    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