1

I need to read some data from binary file, which i save the data pointer in a vector.

I want to handle them with best performance.

I have two design, please see this:

struct A {
  int a, b,c;
}
void Handle(const A & a) {
// do something
}

void Handle(A * a) {

}
std::vector<A* > av; // this is read from file
for (int i = 0; i < 1000; ++i) {
  // is there any difference between these two method? !!!!
  // Handle(av[i]);
  // Handle(*(av[i]))  // does this create a temp variable which speed down the code?
}

I want to know is there any difference between them? and which is faster?

nick
  • 832
  • 3
  • 12
  • 1
    Why would you store pointers in a vector, not the actual data? – KamilCuk May 23 '21 at 08:39
  • 3
    The compiler has more liberty to make optimizations on `Handle(const A &a)` simply because of the `const` keyword. If you declare the other one `Handler(const A* a)` you'd probably get identical results. Same for `Handler(const A* const a)` – selbie May 23 '21 at 08:40
  • @KamilCuk because the data comes from other function. i need to save them and pass here. this code is a demo, the real code make me to do like this – nick May 23 '21 at 08:42
  • 2
    Why does it matter if the data comes from another function? Please make a [mre]. – Ted Lyngmo May 23 '21 at 08:42
  • 1
    Summon the godbolt: [pass by pointer](https://godbolt.org/z/YeErd44zx) | [pass by reference](https://godbolt.org/z/fKW4dKK6e) | [different ways to define Handle](https://godbolt.org/z/TxE5eoxcj) | – selbie May 23 '21 at 09:06
  • 1
    But in case it's not obvious, the compiler doesn't generate code any differently between pass by pointer vs. pass by reference. The language lawyers might say a future implementation "could". But in practice, there's not an architecture where it makes a difference. – selbie May 23 '21 at 09:06

1 Answers1

3

Pointer and reference are mostly the same when regarding performance: their implementation in the runnable code is the same (or course, there are exceptions to this rule, but I cannot think of any).

The difference between reference and pointer is mostly for the programmer - reference has cleaner syntax (that is, you don't need to dereference it when using data), while pointers support nullptr value and pointer arithmetic. The general style rule is to "use references when you can, and pointers when you must".

It is also possible to convert from pointer to reference and back, so these choices are equally powerful when writing code. For example:

void Handle(A& a)
{
    std::cout << a.field;
    another_function_which_receives_reference(a);
    another_function_which_receives_pointer(&a);
}

void Handle(A* a)
{
    std::cout << a->field;
    another_function_which_receives_reference(*a);
    another_function_which_receives_pointer(a);
}

Also, const vs no const works equally well with pointers and references.

anatolyg
  • 26,506
  • 9
  • 60
  • 134