Is it faster to pass the pointer to a vector than the vector itself?

Viewed 803

In my programm I have a function that takes multiple vectors as arguments. I used to pass them as normal vectors so like the definition of the function starts like this:

void do(std::vector<int> a, std::vector<int> b, std::vector<int> c){

and the call looks like this:

do(d, e, f);

but I want my code to be as fast as possible so I wondered whether passing not the vectors but pointers to the vectors would be faster. So the definition of the funtion would look something like this:

void do(std::vector<int> *a, std::vector<int> *b, std::vector<int> *c){

and the call like this:

do(&d, &e, &f);

Does this change make a difference in performance? If yes: positive or negative and is it a big difference if my vectors contain just 3 elements?

2 Answers

Consider the C++ Core Guideline F.16: For “in” parameters, pass cheaply-copied types by value and others by reference to const.

What is cheap and what is expensive to pass by copy depends on some factors. A good rule of thumb is to pass anything as big as a pointer or smaller by value and anything bigger by reference. A std::vector is certainly better passed by const reference instead of making a copy.

You should only pass a pointer instead of a reference when passing a nullptr is a valid parameter. When the caller should always pass a vector and never not a vector then you should prefer references over pointers. References cannot be null, they always refer to an object.


Note that sometimes there is no point in avoiding the copy when the function makes a copy of the argument anyhow. Consider:

 void foo(const std::vector<int>& a) { 
      auto copy = a;
      // ...
 }

Then with

 void foo(std::vector<int> a) {
      // a is already a copy
      // ...
 }

it is more obvious that the function is making a copy, while nothing is saved by passing by reference.

Related