Ternary operator is twice as slow as an if-else block?

后端 未结 10 978
无人及你
无人及你 2020-11-30 16:20

I read everywhere that ternary operator is supposed to be faster than, or at least the same as, its equivalent if-else block.

However, I di

10条回答
  •  日久生厌
    2020-11-30 17:04

    The assembler code generated will tell the story:

    a = (b > c) ? 1 : 0;
    

    Generates:

    mov  edx, DWORD PTR a[rip]
    mov  eax, DWORD PTR b[rip]
    cmp  edx, eax
    setg al
    

    Whereas:

    if (a > b) printf("a");
    else printf("b");
    

    Generates:

    mov edx, DWORD PTR a[rip]
    mov eax, DWORD PTR b[rip]
    cmp edx, eax
    jle .L4
        ;printf a
    jmp .L5
    .L4:
        ;printf b
    .L5:
    

    So the ternary can be shorter and faster simply due to using fewer instructions and no jumps if you are looking for true/false. If you use values other than 1 and 0, you will get the same code as an if/else, for example:

    a = (b > c) ? 2 : 3;
    

    Generates:

    mov edx, DWORD PTR b[rip]
    mov eax, DWORD PTR c[rip]
    cmp edx, eax
    jle .L6
        mov eax, 2
    jmp .L7
    .L6:
        mov eax, 3
    .L7:
    

    Which is the same as the if/else.

提交回复
热议问题