Daniel Oliveira Daniel Oliveira - 1 month ago 22
C++ Question

C++ Return Performace

I have a question about performance. I think this can also applies to other languages (not only C++).

Imagine that I have this function:

int addNumber(int a, int b){
int result = a + b;
return result;
}


Is there any performance improvements if I right the code above like this?

int addNumber(int a, int b){
return a + b;
}


I have this question because the seconds code doesn´t declare a 3rd variable. But would the compiler detect this in the first code?

Answer

To answer this question you can look at the generated assembler code. With -O2, x86-64 gcc 6.2 generates exactly the same code for both methods:

addNumber(int, int):
    lea     eax, [rdi+rsi]
    ret
addNumber2(int, int):
    lea     eax, [rdi+rsi]
    ret

Only without optimization turned on, there is a difference:

addNumber(int, int):
    push    rbp
    mov     rbp, rsp
    mov     DWORD PTR [rbp-20], edi
    mov     DWORD PTR [rbp-24], esi
    mov     edx, DWORD PTR [rbp-20]
    mov     eax, DWORD PTR [rbp-24]
    add     eax, edx
    mov     DWORD PTR [rbp-4], eax
    mov     eax, DWORD PTR [rbp-4]
    pop     rbp
    ret
addNumber2(int, int):
    push    rbp
    mov     rbp, rsp
    mov     DWORD PTR [rbp-4], edi
    mov     DWORD PTR [rbp-8], esi
    mov     edx, DWORD PTR [rbp-4]
    mov     eax, DWORD PTR [rbp-8]
    add     eax, edx
    pop     rbp
    ret

However, performance comparison without optimization is meaningless

Comments