Ilia Choly
Ilia Choly

Reputation: 18557

C++ do inline functions prevent copying?

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.

Upvotes: 3

Views: 491

Answers (2)

segfault
segfault

Reputation: 5939

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.

Upvotes: 1

NPE
NPE

Reputation: 500933

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.

Upvotes: 5

Related Questions