Paul Manta
Paul Manta

Reputation: 31567

How expensive is it to copy a map?

I have a map<EntityState, boost::weak_ptr<Animation>> in my EntityRepresentation class. I would kinda want to create a Builder class for the representation, but I have to consider the costs of copying the map.

EntityState is cheap to copy since it's just a collection of static functions; boost::weak_ptr is also cheap to copy. How about the map as a whole?

Upvotes: 6

Views: 2057

Answers (4)

Matthieu M.
Matthieu M.

Reputation: 299800

I am surprised that no-one else mentionned Copy Elision already.

This concept allows a compiler to elide the copy when possible. It is thus possible that your builder implementation would simply build your EntityRepresentation right into the "return" slot and avoid all copy. At which point your worry would be moot.

Upvotes: 1

James Kanze
James Kanze

Reputation: 153909

I wouldn't worry about it until the profiler says you have to, but generally speaking, there will be one allocation per element in the map, which could have a significant impact.

Upvotes: 0

Gilad Naor
Gilad Naor

Reputation: 21516

Don't optimize prematurely. In many scenarios the run-time performance of a builder class will not be the bottleneck.

Generally, the complexity of copying a map is O(n). From the comments, it looks like n is small. If you've identified that you really need to optimize, then in such a case, using two vectors will be cheaper both in accessing the items, and in the copying.

Upvotes: 4

Cem Kalyoncu
Cem Kalyoncu

Reputation: 14593

It depends on the number of items it has. I don't think its own members will cause much problem.

Upvotes: 2

Related Questions