C++ do inline functions prevent copying?

ぐ巨炮叔叔 提交于 2020-02-02 05:49:41

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!