Home > Mobile >  Performance of std::vector::swap vs std::vector::operator=
Performance of std::vector::swap vs std::vector::operator=

Time:02-01

Given two vectors of equal length:

std::vector<Type> vec1;
std::vector<Type> vec2;

If the contents of vec2 need to be replaced with the contents of vec1, is it more efficient to use

vec2.swap(vec1);

or

vec2 = vec1;

assuming that vec1 will remain in memory but its contents after the operation don't matter? Also, is there a more efficient method that I haven't considered?

CodePudding user response:

swap will be more efficient since no copy is made. = will create a copy of vec1 in vec2, keeping the original intact.

If you check the documentation, you'll see that swap is constant while = is linear.

CodePudding user response:

The most expressive way, which is also optimally efficient, is:

vec2 = std::move(vec1);

In practice this will probably leave vec1 empty, but basically it just means you don't care about its content anymore, you want that moved to vec2.

It's as efficient as swap, and much more efficient than copy assignment.

  •  Tags:  
  • Related