if-else vs if performance

if-else vs if performance

本文关键字:performance if vs if-else      更新时间:2023-10-16

假设我想要一个程序,它从任何设备输入一个数字,如果该数字为0,则返回-1,但在所有其他情况下继续执行该程序。

在c++中,部分代码将是:

int main() {
    if(number == 0) return -1;
    /*
        Here the rest of the program
    */
    return 0; // End of program
}

int main() {
    if(number == 0) return -1;
    else {
        /*
            Here the rest of the program
        */
    }
    return 0; // End of program
}

我的问题是,这些代码部分中哪一个更有效?

是的,我只讨论这种情况,当程序满足特定条件时,您需要退出程序

由于生成的代码完全相同,因此没有性能差异:

$ echo "int main() { int number; if (number == 0) return -1; return 0; }" | g++ -x c++ -S - -o /dev/stdout | md5sum
9430c430d1f748cc920af36420d160ce  -
$ echo "int main() { int number; if (number == 0) return -1; else {} return 0; }" | g++ -x c++ -S - -o /dev/stdout | md5sum
9430c430d1f748cc920af36420d160ce  -
$ echo "int main() { int number; if (number == 0) return -1; else {} return 0; }" | g++ -x c++ -S - -o /dev/stdout 
    .file   ""
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    cmpl    $0, -4(%rbp)
    jne .L2
    movl    $-1, %eax
    jmp .L3
.L2:
    movl    $0, %eax
.L3:
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4"
    .section    .note.GNU-stack,"",@progbits

我看不出在效率方面有什么特别的不同。我认为第一个代码正在做同样的事情,并且不需要else,因为如果输入是0,编译器已经返回了-1

关闭编译器优化后,在某些情况下if比if-else更快。

这是因为在运行时可能的条件跳转少了一次。最好这样表示:

if(condition){
    /*code*/
}
else{
    //Jump 1
    /*code*/
}
//Jump 2
Vs:

if(conditional){
    /*code*/
}
//Jump 1
/*code*/

在编译器优化的情况下,性能上应该没有什么区别,因为编译器会在可能的情况下为你做这些。如果可以的话,硬件上的分支预测也会尝试只使用其中一条语句,并且只有在使用其他选项时才会出现性能影响。

if-else语句用于决策,我想你已经知道了。

不要将整个程序或大部分程序写在else块中,因为如果if-else语句出错,将永远无法访问该代码。

if-else路由基本上是更好的,特别是当与else if一起使用时。它们都是有效的,但是使用括号(良好的实践/组织)

归根结底,它们是相同的语句,具有相同的效果,但这取决于您想要达到的目的。

就像我前面说的,不要在else块中编写程序的其余部分。如果这样,应用程序不能正常运行的风险会高得多。

if(number == 0)
{
    return -1;
}

在您的示例中,该语句单独将是最佳路由。