1

Is there any performance difference between passing a pointer and passing a variable by reference? I'm assuming internally they're both using pointers but was wondering if there are any minor differences.

E.g

int v = 5;

by pointer

void MyFunc(int* P);
MyFunc(&v);

or by reference

void MyFunc(int& R);
MyFunc(v);
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
Prodigle
  • 1,757
  • 12
  • 23
  • Why don't you check the produced assembly to be sure? No, there is no difference. – DeiDei Nov 16 '18 at 11:41
  • 1
    You'd have to disassemble the code, standard says nothing about how references are implemented. I would tend to assume references are implemented as pointers and use them to prevent potentially unnecessary overhead in your function implementation i.e. `if(ptr)`. – George Nov 16 '18 at 11:43
  • 6
    `int *p = 5;` would be a terribly bad idea ... `p` is now pointing at address 5 ... – Ted Lyngmo Nov 16 '18 at 11:43
  • 4
    Also in your example, both `MyFunc` calls take a pointer. – George Nov 16 '18 at 11:45
  • 2
    That really depends on your compiler. Theoretically, there is nothing stopping a compiler from passing references and pointers using different mechanisms. Practically, I've yet to come across a compiler that represents them differently in machine code. – Peter Nov 16 '18 at 11:46

1 Answers1

-1

Both methods will have comparable performance.

Pointers and references are syntactically different but they are identical in terms of runtime performance and generated code in most of the time.

bogdan tudose
  • 1,064
  • 1
  • 9
  • 21