Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++: efficient way to use a vector returned by a function

Suppose we have a vector called V of type vector<int> which is a private member of a class.

We also have this public function of the class:

 vector<int> getV(){ return V; }

now if I have an instance of this class and all I wanted to do is read the values and find the sum of all the values inside the vector,

I could say something like this:

 MyClass obj;
 //update vector
 size_t i, size;
 size = obj.getV().size();
 int sum = 0;
 for(size_t i = 0; i < size; i++){
     sum += obj.getV().at(i);
 }

or I could say something like this:

  MyClass obj;
 //update vector
 size_t i, size;
 vector<int> myV = obj.getV();
 size = myV.size();
 int sum = 0;
 for(size_t i = 0; i < size; i++){
     sum += myV[i];
 }

in the second case we copy the whole vector to vector myV. However, I'm not sure what exactly happens in the first case, do we use the vector as it already is or do we actually copy the vector every time we call the function getV()?

If no copying occurs, then I believe the first version is more efficient.

However I'm not 100% what exactly is happening.

I guess we could avoid doing any copying at all if we returned a reference to the vector V. So we could have the following function:

vector<int>* getV { return &V; }

and then

 MyClass obj;
 //update vector
 size_t i, size;
 vector<int> * myV = obj.getV();
 size = myV->size();
 int sum = 0;
 for(size_t i = 0; i < size; i++){
     sum += myV->at(i);
 }

however I would like to know what exactly is happening in the first case. Is there anything being copied? Even in the third case we return a pointer, so there is some kind of copying happening.

Thank you in advance

like image 636
ksm001 Avatar asked Dec 04 '25 18:12

ksm001


1 Answers

In principal, in the first case you are receiving a copy of the entire vector, calling size() on it, and then it goes out of scope immediately.

In practice, this is so common that modern compilers may be able to recognize it and optimize the copy out entirely. You can read more about this here, for example. The only way to know what's happening on your machine would be to read the compiled assembly code. EDIT: or to do a stack trace as Named did. :)

In the third case, the only thing you're copying is the value of the pointer, which is either 4 or 8 bytes (8 on a 64bit operating system).

If you're worried about efficiency, the best thing to do is always: try it both ways and see which is faster.

like image 122
Corey Avatar answered Dec 06 '25 06:12

Corey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!