N
N
Nikita2022-04-10 23:59:12
C++ / C#
Nikita, 2022-04-10 23:59:12

Will std::swap(vector[0], vector[1]) be faster than vector[1] = vector[0]?

Let's say we have a vector of two elements. You need to replace the value in the first element of the vector with the value in the zero element of the vector. What will be stored after the operation in the null element does not matter. Then which of these options would be faster? It is clear that specifically in this example with a small vector, the difference in speed does not matter, but I am solving a problem where there will be a huge vector and it will be necessary to perform a huge number of such operations.

std::swap(vector[0], vector[1]);

vector[1] = vector[0];

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2022-04-11
@gth-other

In general, it will.
std::swap works for a constant:

Complexity
1) Constant.

Assignment per line :
Complexity
1) Linear in the size of *this and other.

Edit: this is if the assigned pieces are vectors. Or some large objects with move semantics. If you have stupid numbers, then one assignment will be faster than swap.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question