'Is there a performance difference between assigning before returning and directly returning in C++?
Is there a performance difference between the two following functions, or is it handled by the compiler the same?
double f1(double a, double b) {
return a + b;
}
double f2(double a, double b) {
double sum = a + b;
return sum;
}
Thanks.
Solution 1:[1]
Is there a performance difference between the two following functions
One function contains two statements and the other contains one statement.
or is it handled by the compiler the same?
They can be. Both functions have identical observable behaviour, so they may produce an identical program.
Solution 2:[2]
From the practical side, it helps to see what compilers actually do with such a piece of code, see this godbolt.
Turns out that starting from `-O1ยด optimization level, g++ and clang for example create the exact same assembler instructions:
addsd xmm0, xmm1
ret
Meaning the performance would of course also be exactly the same.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | eerorika |
| Solution 2 | codeling |
