Search code examples
arrayscperformanceconditional-operatormicro-optimization

Ternary operator vs array?


In C, is indexing an array faster than the ?: operator?

For example, would (const int[]){8, 14}[N > 10] be faster than N > 10? 14 : 8?


Solution

  • Use of the compound literal (and array in general) will be much less efficient as arrays are created (by current real-world compilers) despite the optimization level. Worse, they're created on the stack, not just indexing static constant data (which would still be slower, at least higher latency, than an ALU select operation like x86 cmov or AArch64 csel which most modern ISAs have).

    I have tested it using all compilers I use (including Keil and IAR) and some I don't use (icc and clang).

    int foo(int N)
    {
        return (const int[]){8, 14}[N > 10]; 
    }
    
    int bar(int N)
    {
        return  N > 10? 14 : 8;
    }
    
    foo:
            mov     rax, QWORD PTR .LC0[rip]     # load 8 bytes from .rodata
            mov     QWORD PTR [rsp-8], rax       # store both elements to the stack
            xor     eax, eax                      # prepare a zeroed reg for setcc
            cmp     edi, 10
            setg    al                            # materialize N>10 as a 0/1 integer
            mov     eax, DWORD PTR [rsp-8+rax*4]  # index the array with it
            ret
    
    bar:
            cmp     edi, 10
            mov     edx, 8               # set up registers with both constants
            mov     eax, 14
            cmovle  eax, edx             # ALU select operation on FLAGS from CMP
            ret
    .LC0:
            .long   8
            .long   14
    

    https://godbolt.org/z/qK65Gv