如果语句为真,跳过 if
语句是否更快?例如:
if (a = true) {
blah blah...
goto end;
} else {
blah blah..
}
label: end;
这段代码会不会比:
if (a = true) {
blah blah...
} else {
blah blah..
}
最佳答案
如果任何体面的编译器没有为这两种可能性发出相同的汇编程序,我会感到惊讶。这是一个编译和运行的简单 C 程序:
#include <stdio.h>
int main(void)
{
int c = getchar();
if (c == 'y') {
++c;
goto end;
} else {
--c;
}
end:
putchar(c);
putchar('\n');
return 0;
}
用 gcc -S
编译,没有优化标志,这里是输出:
.file "goto_skip_41709548.c"
.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
subq $16, %rsp
call getchar
movl %eax, -4(%rbp)
cmpl $121, -4(%rbp)
jne .L2
addl $1, -4(%rbp)
jmp .L3
.L2:
subl $1, -4(%rbp)
.L3:
movl -4(%rbp), %eax
movl %eax, %edi
call putchar
movl $10, %edi
call putchar
movl $0, %eax
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu 4.9.4-2ubuntu1~14.04.1) 4.9.4"
.section .note.GNU-stack,"",@progbits
对于删除了 goto
的相同代码,编译器给出了完全相同的输出。使用 diff
验证:
λ> diff w_goto.s wo_goto.s
1c1
< .file "goto_skip_41709548.c"
---
> .file "no_goto_skip_41709548.c"
关于c - 使用 goto 跳过 if 语句是否更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41709548/