Search code examples
c++vectorreferencecontainersoverhead

What is the overhead of this operation to modify by reference in C++?


Let's say there is a large vector called second, and now I want my own vector first to point to the large vector. I wrote this code:

#include <iostream>
#include <vector>

std::vector<int> second (100000,100);
void modify(std::vector<int>& i) {
  i = second;
}
int main ()
{
  std::vector<int> first(1, 1); 
  modify(first);    
  return 0;
}

Is it true that there is an overhead for modify function? Will the content of second to be cloned into a new array and then passed into first, or is it just passed by reference with negligible overhead?


Solution

  • Yes, this will copy the entire vector, and the complexity is linear in size of second, as stated in the ref.

    What you did avoid by passing a reference as the function parameter is copying first into the parameter i. In other words, if your function was this (passing the vector by value-which would change the semantic of the function):

    // more expensive!
    void modify(std::vector<int> i) {
      i = second;
    }
    

    then you would pay the cost of copying first to i, plus the cost of copying second to i. Of course in your code, this would make no difference, since i is tiny, but in general it's a good practice to pass large objects by reference, in order to avoid unnecessary copies.


    Tip: Study move semantics.