Is there a performance difference between i++ and ++i in C++?

前端 未结 17 2028
臣服心动
臣服心动 2020-11-21 17:15

We have the question is there a performance difference between i++ and ++i in C?

What\'s the answer for C++?

17条回答
  •  无人及你
    2020-11-21 17:52

    Both are as fast ;) If you want it is the same calculation for the processor, it's just the order in which it is done that differ.

    For example, the following code :

    #include 
    
    int main()
    {
        int a = 0;
        a++;
        int b = 0;
        ++b;
        return 0;
    }
    

    Produce the following assembly :

     0x0000000100000f24 : push   %rbp
     0x0000000100000f25 : mov    %rsp,%rbp
     0x0000000100000f28 : movl   $0x0,-0x4(%rbp)
     0x0000000100000f2f :    incl   -0x4(%rbp)
     0x0000000100000f32 :    movl   $0x0,-0x8(%rbp)
     0x0000000100000f39 :    incl   -0x8(%rbp)
     0x0000000100000f3c :    mov    $0x0,%eax
     0x0000000100000f41 :    leaveq 
     0x0000000100000f42 :    retq
    

    You see that for a++ and b++ it's an incl mnemonic, so it's the same operation ;)

提交回复
热议问题