Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any performance differences between std::copy and the container's copy constructor?

std::copy is a more general approach since it can handle containers with differing value types (e.g. copy from std::vector<float> to std::vector::<double>). But when the value type is the same for both containers, does it matter whether I use the copy constructor instead of std::copy?

like image 993
marcos assis Avatar asked Nov 04 '14 19:11

marcos assis


2 Answers

Don't worry about performance, they should all be super close. Instead:

  • If you're creating a new container that's a copy, use the copy constructor or two-iterator constructor (if different element types).
  • If you're replacing (assigning) an existing container, use the appropriate assignment operator or assign member.
  • If you're replacing a subset of elements, use std::copy.

By accurately representing what you're trying to do, you give the compiler the most possible information to optimize its code (for example constructing directly from an existing container it can pre-allocate exactly the right about of memory).

like image 172
Mark B Avatar answered Oct 13 '22 06:10

Mark B


One potentially important difference is when you have a situation where you are able to invoke the move constructor rather than the copy constructor (e.g. when the object you are copy constructing from is an rvalue, such as the return value of a function). If you have such a situation, you definitely want to make sure you take advantage of it by move constructing or move assigning rather than using std::copy.

Basically this is just another reason to follow Mark B's advice.

like image 44
mattnewport Avatar answered Oct 13 '22 06:10

mattnewport