在我们的c++课程中,他们建议不要再在新项目中使用c++数组。据我所知,Stroustroup本人建议不要使用数组。但是否存在显著的性能差异?
当前回答
可能会有一些边缘情况,你在内联函数中有一个向量访问在内联函数中,你已经超出了编译器将内联的范围,它将强制函数调用。这种情况太罕见了,不值得担心——总的来说,我同意litb的观点。
我很惊讶居然没有人提到这一点——不要担心性能,直到它被证明是一个问题,然后进行基准测试。
其他回答
如果使用向量表示多维行为,则会对性能造成影响。
2d+向量会导致性能下降吗?
其要点是,每个子向量都有大小信息,因此会有少量开销,并且不一定会有数据序列化(与多维c数组不同)。这种串行化的缺乏可以提供比微优化更大的机会。如果你在做多维数组,最好扩展std::vector并滚动你自己的get/set/resize bits函数。
如果不需要动态调整大小,则会有存储容量的内存开销(一个指针/size_t)。就是这样。
下面是简单的测试:
c++数组vs 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.
有时候数组确实比向量好。如果你总是在操纵别人 固定长度的对象集合,数组更好。考虑下面的代码片段:
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++)。
推荐文章
- 如何读一个文本文件到一个列表或数组与Python
- cplusplus.com给出的错误、误解或坏建议是什么?
- 如何在Python中将十六进制字符串转换为字节?
- 找出质数最快的算法是什么?
- 与push()相反;
- 用“+”(数组联合运算符)合并两个数组如何工作?
- c++枚举类可以有方法吗?
- 使arrayList.toArray()返回更具体的类型
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- 在函数的签名中添加关键字