if(a() && b() && c() && d()) doSomething(); if(a()) if(b()) if(c()) if(d()) doSomething();
这两者之间是否存在“任何”性能差异?
例如,在a()变为0的情况下,它是否会在第一个if语句中继续运行b(),c()和d()?或者它会与第二个嵌套的if语句一样工作吗?
解决方法
它们完全相同.
要自己测试一下,运行gcc -S test.c(假设这是你放置源代码的地方)并观察test.s.的内容.
以下是嵌套if方法如何使用默认选项(带注释注释)在gcc 4.8.1中编译:
main: .LFB0: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6,-16 movq %rsp,%rbp .cfi_def_cfa_register 6 movl $0,%eax call A # try to call A testl %eax,%eax # look at its return value je .L3 # short-circuit if it returned 0 movl $0,%eax # ...repeat for B,et al. call B testl %eax,%eax je .L3 movl $0,%eax call C testl %eax,%eax call D testl %eax,%eax call doSomething .L3: popq %rbp .cfi_def_cfa 7,8 ret .cfi_endproc
这是和&&方法编译:
main: .LFB0: .cfi_startproc pushq %rbp .cfi_def_cfa_offset 16 .cfi_offset 6,%eax call A # try to call A testl %eax,%eax # look at its return value je .L3 # short-circuit if it returned 0 movl $0,%eax # ...repeat for B,8 ret .cfi_endproc