简体   繁体   English

C ++:指针向量与固定大小的数组性能

[英]C++: Vector of pointers vs Fixed-size array performance

Performance-wise, which is faster? 性能方面,哪个更快?

A vector of object pointers allocated by the new operator? 新操作符分配的对象指针的向量?

std::vector<Object *> array;

Or an array allocated with new in the constructor? 还是在构造函数中分配了new的数组?

Object[] objects;
objects = new objects[64];

The idea is that in every frame, the program loops through each element reading/writing values for each element. 想法是,在每个帧中,程序都会循环遍历每个元素,以读取/写入每个元素的值。

Edit: 编辑:

The second snippet was pulled from an XNA book. 第二段摘自XNA书。 I am not using XNA to write my framework, and I'm trying to figure out the best method for using containers in an application that requires speed. 我没有使用XNA编写框架,而是试图找出在需要速度的应用程序中使用容器的最佳方法。

Definitely the second one. 绝对是第二个。

  • With a vector of pointers, each individual element of that vector can be allocated anywhere on the heap. 使用指针向量,可以将向量的每个单独元素分配到堆上的任何位置。

  • With an array of objects, all elements are stored sequentially. 对于对象数组,所有元素都按顺序存储。 This means the processor can cache chunks of memory more effectively as you iterate through the array. 这意味着当您遍历数组时,处理器可以更有效地缓存内存块。

The concept is called cache locality , referring to how well organised your data is with respect to memory access patterns and caching. 该概念称为缓存局部性 ,指的是数据在内存访问模式和缓存方面的组织度。

As pointed out in the comments, neither of your examples are correct. 正如评论中指出的那样,您的示例都不正确。 I assume you meant something like this: 我认为您的意思是这样的:

std::vector<Object*> vector_of_pointers(size);

Object *array_of_objects = new Object[size];

However, I fear you may not have phrased your question the way you intended. 但是,我担心您可能没有按照您的意图表达您的问题。 You're not comparing two similar things. 您没有在比较两个相似的东西。 A vector is basically just an array that can grow if necessary. 向量基本上只是一个数组,必要时可以增长。 It makes all the same guarantees as an array, and so if it's storing the same data type, you shouldn't notice any difference between the two. 它与数组具有所有相同的保证,因此,如果存储相同的数据类型,则您不会注意到两者之间的任何区别。

// Bad cache locality:
Object **A = new Object*[size];
std::vector<Object*> B(size);

// Good cache locality:
Object *C = new Object[size];
std::vector<Object> D(size);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM