在我们的c++课程中,他们建议不要再在新项目中使用c++数组。据我所知,Stroustroup本人建议不要使用数组。但是否存在显著的性能差异?


当前回答

下面是简单的测试:

c++数组vs Vector性能测试说明

与“对向量和数组/指针的基本索引、解引用和增量操作生成的汇编代码的比较”的结论相矛盾。

数组和向量之间一定有区别。测试是这么说的…试试吧,代码就在那里……

其他回答

选择STL。没有性能损失。这些算法非常高效,它们在处理我们大多数人不会想到的细节方面做得很好。

对于定长数组,在发布版本中性能是相同的(相对于vector<>),但在调试版本中,根据我的经验,低级数组的优势是20倍(MS Visual Studio 2015, c++ 11)。

因此,如果您(或您的同事)倾向于在数组使用中引入错误,那么支持STL的“节省调试时间”参数可能是有效的,但如果您的调试时间主要用于等待代码运行到您当前正在处理的位置,以便您可以逐步检查它,则可能不是有效的。

处理数字密集型代码的有经验的开发人员有时属于第二组(特别是如果他们使用vector:))。

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++代码。但是,请记住,在这种情况下,大多数赌注都是无效的,您将再次处理原始内存。

有时候数组确实比向量好。如果你总是在操纵别人 固定长度的对象集合,数组更好。考虑下面的代码片段:

int main() {
int v[3];
v[0]=1; v[1]=2;v[2]=3;
int sum;
int starttime=time(NULL);
cout << starttime << endl;
for (int i=0;i<50000;i++)
for (int j=0;j<10000;j++) {
X x(v);
sum+=x.first();
}
int endtime=time(NULL);
cout << endtime << endl;
cout << endtime - starttime << endl;

}

X的向量在哪里

class X {
vector<int> vec;
public:
X(const vector<int>& v) {vec = v;}
int first() { return vec[0];}
};

X的数组版本为:

class X {
int f[3];

public:
X(int a[]) {f[0]=a[0]; f[1]=a[1];f[2]=a[2];}
int first() { return f[0];}
};

数组版本的main()将更快,因为我们避免了 每次在内部循环中“new”的开销。

(此代码由我发布到comp.lang.c++)。