marcos assis
marcos assis

Reputation: 388

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?

Upvotes: 10

Views: 1766

Answers (2)

Mark B
Mark B

Reputation: 96241

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).

Upvotes: 16

mattnewport
mattnewport

Reputation: 14057

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.

Upvotes: 1

Related Questions