开发者

C++ Container performance question

What would have better performance, a stl vector, or a dynam开发者_Go百科ic array that's just realloc'd everytime I want to add something to it?

Would using vectors::iterator be faster then using a for loop on an array?

And if someone could explain why, that would be great.


Premature optimization is evil. The standard C++ way of doing things is to use the standard library containers as much as possible. If you want to use the best containers fitting your needs: here is the diagram

C++ Container performance question

source: Original Image by Jameson Williams

One day you will maybe need to heavily optimize and use a dynamic array, but it should be rare.... one day you will also need collection that are multi-thread safe... and so on... but in general std containers are the way to go.


What would have better performance, a stl vector, or a dynamic array that's just realloc'd everytime I want to add something to it?

Stl vectors have insertion in amortized constant time (because reallocation is not done all the time and reservations occur by factor 1.5 (minimum)).

Therefore according to your description, vectors will be massively faster than reallocating all the time

Would using vectors::iterator be faster then using a for loop on an array?

In the general case: exactly identical. However certain STL implementations generate checks in debug mode that can considerably slow down the use of container iterators.

(note most implementations implement vector/string iterators as a typedef to value_type*)

And if someone could explain why, that would be great.


What would have better performance, a stl vector, or a dynamic array that's just realloc'd everytime I want to add something to it?

stl vector should be the winner in this case, because it doesn't realloc every time[vector guarantees O(1) amortized insert time]. However, it might be similar if your malloc implementation is optimized for this kind of usage.

Would using vectors::iterator be faster then using a for loop on an array?

These should be the same, particularly because vector::iterator are usually just pointers into an array or thin wrappers thereof.


There is no difference in speed, but vector is massively safer. This is because the functions will just be inlined by your compiler, but vector carries a large number of exception and bounds-checking (if you ask for it) gurarantees that you won't see when using your own raw arrays.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜