0

What is the fastest and most efficient way to copy contents of one vector to another? I am thinking of something where the vector sizes will be relatively large and copies will happen frequently. One assumption is that the vector sizes won't be changing between calls and the two vectors will be equal in size.

As such, is there a speed difference between the following? Is there a better way to do it?

vector<float> v1(100);
vector<float> v2(100);
// case 1
v2 = v1;
// case 2
v2.assign(v1.begin(), v1.end());
// case 3
for(int x = 0; x < v1.size(); x++)
    v2[x] = v1[x];
// case 4
memcpy(&v2[0], &v1[0], v1.size()*sizeof(float));
BigBrownBear00
  • 1,378
  • 2
  • 14
  • 24
  • 2
    You can test it yourself and find out. – NathanOliver Jul 29 '16 at 13:32
  • 3
    Do you care about v2 afterwards? Because `v1.swap(v2)` is pretty much instant. – MSalters Jul 29 '16 at 13:33
  • Possible duplicate of [fast way to copy one vector into another](http://stackoverflow.com/questions/644673/fast-way-to-copy-one-vector-into-another) – abhishek_naik Jul 29 '16 at 13:34
  • 1
    This is a job for... [Google Benchmark](https://github.com/google/benchmark) ! – Richard Dally Jul 29 '16 at 13:35
  • I believe I saw that MSVC is now using SFINEA to actually use `memcpy` in assignment when the type was `memcpy`-able – NathanOliver Jul 29 '16 at 13:39
  • @MSalters sometimes I will need v2, sometimes I won't. – BigBrownBear00 Jul 29 '16 at 14:04
  • @NathanOliver while true, I was hoping for deeper insight than an empirical test – BigBrownBear00 Jul 29 '16 at 14:05
  • I doubt you will get it. There are many different implementations and optimizations they could do where one way may be faster on X but slower on Y. I like to first code for maintainability and clarity. After that profile and determine if there really is a bottle neck there. Compilers are getting very good at optimizing code with clear intentions. – NathanOliver Jul 29 '16 at 14:08

0 Answers0