问题
Assuming the compiler does in fact inline foo
is there a performance difference between these 2 statements?
inline int foo (int val) {
return val;
}
int main () {
std::cout << foo(123) << std::endl;
std::cout << 123 << std::endl;
return 0;
}
Let's ignore any implications that move semantics and copy elision might have.
回答1:
My compiler (gcc 4.7.2) produces nearly identical code for the two statements:
_main:
LFB1018:
pushq %rbx
LCFI0:
movq __ZSt4cout@GOTPCREL(%rip), %rbx
; std::cout << foo(123) << std::endl;
movl $123, %esi
movq %rbx, %rdi
call __ZNSolsEi
movq %rax, %rdi
call __ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
; std::cout << 123 << std::endl;
movq %rbx, %rdi
movl $123, %esi
call __ZNSolsEi
movq %rax, %rdi
call __ZSt4endlIcSt11char_traitsIcEERSt13basic_ostreamIT_T0_ES6_
xorl %eax, %eax
popq %rbx
LCFI1:
ret
The only difference is the order of the first two instructions. I've experimented with it, and this difference doesn't appear to have anything to do with foo()
: if I repeat the two lines twice, only the last of the four statements has the instruction order reversed. This makes me think that this artifact probably has something to do with the pipeline optimizer or something of that nature.
回答2:
The should absolutely be the same.
To make sure it is really the case, use the -S
flag in gcc to generate assembly code and compare the two lines manually.
Also, note that inline keyword is just a hint to the compiler, and the compiler may choose to ignore it. This question has an in-depth discussion of using inline.
来源:https://stackoverflow.com/questions/13807098/c-do-inline-functions-prevent-copying