Search code examples
c++performanceif-statementreturn

Which one works faster?


Do these 2 have any differences?

if (condition)
{
    std::cout << "Condition is true";
}
else
{
    std::cout << "Condition is false";
}

OR

if (condition)
{
    std::cout << "Condition is true";
    return 0;
}
std::cout << "Condition is false";

I know that is not good to use the second one because maybe you have some more code after it. But at the end of the code that we don't have anything after that else, isn't it better to use the second one?


Solution

  • I modified the original question a bit as follows,

    void f1() {
        int a = 0;
        if (a > 0) {
            a = 1;
        } else {
            a = 2;
        }
    }
    
    void f2() {
        int a = 0;
        if (a > 0) {
            a = 1;
            return;
        } 
        a = 2;
    }
    

    Here are the compiled assembly. f1() and f2() are nearly identical.

    f1():
            push    rbp
            mov     rbp, rsp
            mov     DWORD PTR [rbp-4], 0
            cmp     DWORD PTR [rbp-4], 0
            jle     .L2
            mov     DWORD PTR [rbp-4], 1
            jmp     .L4
    .L2:
            mov     DWORD PTR [rbp-4], 2
    .L4:
            nop
            pop     rbp
            ret
    f2():
            push    rbp
            mov     rbp, rsp
            mov     DWORD PTR [rbp-4], 0
            cmp     DWORD PTR [rbp-4], 0
            jle     .L6
            mov     DWORD PTR [rbp-4], 1
            jmp     .L5
    .L6:
            mov     DWORD PTR [rbp-4], 2
    .L5:
            pop     rbp
            ret
    

    The only difference is that .L4 has a nop. More details can be found here.