c - 使用 goto 跳过 if 语句是否更快

标签 c

如果语句为真,跳过 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/

相关文章:

c - 采访 : Hash function: sine function

c - 无法链接linux内核模块:警告:“snd_device_new”未定义

c - 为什么“while(!feof(file))”总是错误的?

c++ - 如何在Objective-C/C/C++中进行字符和字节位置的转换

c - 识别gtk中滚动条的向上/向下移动

c - 交叉编译问题

c - 使用数组将数字解码为字母

c - Visual Studio C2085 关于数组定义

c - 如何在C中进行声音合成?

你能从一个特定长度的数组创建一个 c 结构体吗?