当前位置: 动力学知识库 > 问答 > 编程问答 >

C++-style vector - array of pointers or just array?

问题描述:

I'm writing simple template, vector-style class and I'm wondering, which way is better - to collect elements in normal array, or in array of pointers?

Second way should ensure faster copying of array, but needs more memory for pointers.

Am I right? Are there any other performance consequences?

网友答案:

I'm writing simple template, vector-style class and I'm wondering, which way is better - to collect elements in normal array, or in array of pointers?

All std::vector<> implementations choose a "normal array" -- a contiguous allocation of elements. Before considering performance, consider the semantics you need.

Using pointers can greatly complicate your implementation. Also, It would break std::vector<>'s guarantee that the elements are contiguously allocated.

Using pointers means more bookkeeping. Also, it will require additional allocations to maintain and indirection. A simpler structure of simple types can be faster to copy, although using underlying pointers has some advantages. Generally, you should favor the contiguous allocation as a default. If you find a great benefit for the case of pointers, use it in another type.

Also note that vector operations like moves and swaps can just be implemented by swapping the pointers to the array, so you can have pointer speed for some operations.

The existing vector design is a very good starting point.

The big benefit of contiguous allocations is that it is easy on the caches. Memory reads and writes are much faster than having elements' memory scattered all over the place.

Another point: The size of a pointer can be greater than one value/element. In that case, using pointers can multiply the memory demand.

Second way should ensure faster copying of array, but needs more memory for pointers.

How so? You still need to copy elements and keep track of their lifetimes for proper semantics. In that case, a simple vector of shared_ptrs is an approach worth consideration, if your intention is to share the vector's elements. Generally, shared_ptr should be used very little, so you may want to rethink your design. There is absolutely nothing wrong using std::vector<>'s design as a starting point, as it is a great default.

网友答案:

Why are you worrying about performance now? Also, a normal (C-style) array must have compile-time size, and also doesn't really need any fanc memory management, so you really don't have much of a choice.

Also, how would copy speed be related to the underlying data? If there are N bytes, either way would need to copy N bytes.

网友答案:

It seems that you want implement your own vector template? Don't do it, use one of the already existing STL containers instead.

There is a lot more to do than just evaluate the "performance" relevance of pointer vs. flat data decisions.

分享给朋友:
您可能感兴趣的文章:
随机阅读: