在我们的c++课程中,他们建议不要再在新项目中使用c++数组。据我所知,Stroustroup本人建议不要使用数组。但是否存在显著的性能差异?
当前回答
STL is a heavily optimized library. In fact, it's even suggested to use STL in games where high performance might be needed. Arrays are too error prone to be used in day to day tasks. Today's compilers are also very smart and can really produce excellent code with STL. If you know what you are doing, STL can usually provide the necessary performance. For example by initializing vectors to required size (if you know from start), you can basically achieve the array performance. However, there might be cases where you still need arrays. When interfacing with low level code (i.e. assembly) or old libraries that require arrays, you might not be able to use vectors.
其他回答
两者之间的性能差异很大程度上取决于实现——如果你比较一个实现得很差的std::vector和一个优化的数组实现,数组会赢,但是反过来,vector会赢……
As long as you compare apples with apples (either both the array and the vector have a fixed number of elements, or both get resized dynamically) I would think that the performance difference is negligible as long as you follow got STL coding practise. Don't forget that using standard C++ containers also allows you to make use of the pre-rolled algorithms that are part of the standard C++ library and most of them are likely to be better performing than the average implementation of the same algorithm you build yourself.
也就是说,以我之见,vector在使用调试STL的调试场景中胜出,因为大多数具有适当调试模式的STL实现至少可以突出/清除人们在使用标准容器时所犯的典型错误。
哦,不要忘记数组和vector共享相同的内存布局,因此您可以使用vector将数据传递给需要基本数组的遗留C或c++代码。但是,请记住,在这种情况下,大多数赌注都是无效的,您将再次处理原始内存。
选择STL。没有性能损失。这些算法非常高效,它们在处理我们大多数人不会想到的细节方面做得很好。
可能会有一些边缘情况,你在内联函数中有一个向量访问在内联函数中,你已经超出了编译器将内联的范围,它将强制函数调用。这种情况太罕见了,不值得担心——总的来说,我同意litb的观点。
我很惊讶居然没有人提到这一点——不要担心性能,直到它被证明是一个问题,然后进行基准测试。
如果不需要动态调整大小,则会有存储容量的内存开销(一个指针/size_t)。就是这样。
关于杜里的贡献和我自己的测量。
结论是整数数组比整数向量快(在我的例子中是5倍)。然而,对于更复杂/未对齐的数据,数组和向量的速度大致相同。