user2310042
user2310042

Reputation: 95

Container: Vector class.... Slow

Could anybody explain why, in vector container, push_back operation is usually slower? I hear some people say that, but can't find the reason why it is a bit slower.

As a beginner, I would like use vector and push_back but do I other options for better performance? Please let me know. Thanks,

Upvotes: 0

Views: 139

Answers (3)

OGH
OGH

Reputation: 550

The push_back operation is not always slower. It has constant complexity (amortized time). The only time it is slower, is if reallocation occurs. One of the useful things about std::vector is that you can always add objects to the vector, regardless of the size. Let's the vector's capacity is 10 and there are 10 objects in the vector, then reallocation occurs to make the vector bigger. Usually, the vector size is doubled and the objects are copied into the new vector which is a slower operation.

Upvotes: 0

Mike Seymour
Mike Seymour

Reputation: 254751

A vector stores its objects in a contiguous array. It allocates a certain amount of space (its capacity) to contain the objects; when the number of objects (its size) is about to exceed the capacity, it allocates a larger space and copies (or moves) the existing objects across.

This can take some time. To avoid it, and guarantee that push_back and insert don't need to reallocate, you can call reserve to allocate a large enough block for your needs beforehand.

Upvotes: 1

Captain Obvlious
Captain Obvlious

Reputation: 20093

When you append or insert an item into a std::vector there may not be enough room to store it. This causes the vector to allocate enough storage to hold all elements and copies them into the new block of memory. If you are storing objects by value instead of by pointer this a complete copy will be made. For complex types this may be involved and include additional allocations and copying. In situations like this performance can be impacted depending on the size of the vector. For large vectors the performance hit will be much more noticeable.

Upvotes: 0

Related Questions