ManuelSchneid3r
ManuelSchneid3r

Reputation: 16121

Why can std::vector be more performant than a native array?

In a comparison on performance between Java and C++ our professor claimed, that theres no benefit in choosing a native array (dynamic array like int * a = new int[NUM] ) over std::vector. She claimed too, that the optimized vector can be faster, but didn't tell us why. What is the magic behind the vector?

PLEASE just answers on performance, this is not a general poll!

Upvotes: 1

Views: 226

Answers (3)

aaronman
aaronman

Reputation: 18751

Any super optimized code with lower level stuff like raw arrays can beat or tie the performance of an std::vector. But the benefits of having a vector far outweigh any small performance gains you get from low level code.

  1. vector manages it's own memory, array you have to remember to manage the memory
  2. vector allows you to make use of stdlib more easily (with dynamic arrays you have to keep track of the end ptr yourself) which is all very well written well tested code
  3. sometimes vector can even be faster, like qsort v std::sort, read this article, keep in mind the reason this can happen is because writing higher level code can often allow you to reason better about the problem at hand.
  4. Since the std containers are good to use for everything else, that dynamic arrays don't cover, keeping code consistent in style makes it more readable and less prone to errors.

One thing I would keep in mind is that you shouldn't compare a dynamic array to a std::vector they are two different things. It should be compared to something like std::dynarray which unfortunately probably won't make it into c++14 (boost prolly has one, and I'm sure there are reference implementations lying around). A std::dynarray implementation is unlikely to have any performance difference from a native array.

Upvotes: 3

IInspectable
IInspectable

Reputation: 51503

The only performance optimization a std::vector can offer over a plain array is, that it can request more memory than currently needed. std::vector::reserve does just that. Adding elements up to its capacity() will not involve any more allocations.

This can be implemented with plain arrays as well, though.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311088

  1. There is benefit of using vector instead of array when the number of elements needs to be changed.
  2. Neither optimized vector can be faster than array.

Upvotes: 1

Related Questions