在我们的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.
其他回答
关于杜里的贡献和我自己的测量。
结论是整数数组比整数向量快(在我的例子中是5倍)。然而,对于更复杂/未对齐的数据,数组和向量的速度大致相同。
有时候数组确实比向量好。如果你总是在操纵别人 固定长度的对象集合,数组更好。考虑下面的代码片段:
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++)。
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.
当你想要一个未初始化的缓冲区(例如用作memcpy()的目标)时,使用std::vector与使用raw数组肯定会有性能影响。vector将使用默认构造函数初始化其所有元素。原始数组则不会。
c++规范中std:vector构造函数接受count参数(这是第三种形式):
从各种数据源构造一个新容器,可选地使用用户提供的分配器alloc。
使用默认插入的t的count个实例构造容器。
复杂性
2-3)计数线性
原始数组不会产生这种初始化代价。
注意,使用自定义分配器,可以避免vector元素的“初始化”(即使用默认初始化而不是值初始化)。请看这些问题了解更多细节:
这是c++ 11和Boost下vector::resize(size_type n)的行为吗?容器正确吗? 如何避免std::vector<>来初始化它的所有元素?
如果在调试模式下编译软件,许多编译器将不会内联vector的访问器函数。这将使stl向量的实现在性能有问题的情况下变得更慢。它还将使代码更容易调试,因为您可以在调试器中看到分配了多少内存。
在优化模式下,我希望stl向量接近数组的效率。这是因为许多vector方法现在都内联了。
推荐文章
- 如何读一个文本文件到一个列表或数组与Python
- cplusplus.com给出的错误、误解或坏建议是什么?
- 如何在Python中将十六进制字符串转换为字节?
- 找出质数最快的算法是什么?
- 与push()相反;
- 用“+”(数组联合运算符)合并两个数组如何工作?
- c++枚举类可以有方法吗?
- 使arrayList.toArray()返回更具体的类型
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- 将析构函数设为私有有什么用?
- main()中的Return语句vs exit()
- 为什么c#不提供c++风格的'friend'关键字?
- 在函数的签名中添加关键字