在我们的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.
其他回答
下面是简单的测试:
c++数组vs Vector性能测试说明
与“对向量和数组/指针的基本索引、解引用和增量操作生成的汇编代码的比较”的结论相矛盾。
数组和向量之间一定有区别。测试是这么说的…试试吧,代码就在那里……
选择STL。没有性能损失。这些算法非常高效,它们在处理我们大多数人不会想到的细节方面做得很好。
向量是底层的数组。 性能是一样的。
一个可能会遇到性能问题的地方是,vector的大小一开始就不正确。
当一个vector容器被填充时,它将调整自身的大小,这可能意味着,一个新的数组分配,然后是n个复制构造函数,然后是大约n个析构函数调用,然后是一个数组删除。
如果你的构造/销毁是昂贵的,你最好让向量的正确大小开始。
有一种简单的方法可以证明这一点。创建一个简单的类,显示它何时被构造/销毁/复制/赋值。创建一个这些东西的向量,并开始将它们推到向量的后端。当向量被填充时,随着向量大小的调整,将会有一连串的活动。然后再试一次,将向量大小调整为预期的元素数量。你会发现其中的不同。
如果使用向量表示多维行为,则会对性能造成影响。
2d+向量会导致性能下降吗?
其要点是,每个子向量都有大小信息,因此会有少量开销,并且不一定会有数据序列化(与多维c数组不同)。这种串行化的缺乏可以提供比微优化更大的机会。如果你在做多维数组,最好扩展std::vector并滚动你自己的get/set/resize bits函数。
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.