在与同事的讨论中,我最终编写了基准测试来测试std::vector
和原始动态分配数组,并最终得出了一个惊喜的结果。
我的测试如下:
#include "testconsts.h" // defines NUM_INTS across all tests
#include <vector>
int main()
{
const int numInts = NUM_INTS;
std::vector<int> intVector( numInts );
int * const intArray = new int[ numInts ];
++intVector[0]; // force access to affect optimization
++intArray[0]; // force access to affect optimization
for( int i = 0; i < numInts; ++i )
{
++intArray[i];
}
delete[] intArray;
return 0;
}
并且:
#include "testconsts.h" // defines NUM_INTS across all tests
#include <vector>
int main()
{
const int numInts = NUM_INTS;
std::vector<int> intVector( numInts );
int * intArray = new int[ numInts ];
++intArray[0]; // force access to affect optimization
++intVector[0]; // force access to affect optimization
for( int i = 0; i < numInts; ++i )
{
++intVector[i];
}
delete[] intArray;
return 0;
}
使用gcc 4.4.3编译,并使用g++ -O3编译。
多次运行基准测试的结果类似于:
数组:
real 0m0.757s
user 0m0.176s
sys 0m0.588s
向量:
real 0m0.572s
user 0m0.268s
sys 0m0.304s
三个结论非常明显:
- 数组在用户时间上更快
- 向量在系统时间上更快
- 总体而言,向量赢得了这场竞争
std::vector
在构造时默认初始化元素,而你代码中的new
没有这样做。数组测试承担了两个容器的成本,而向量测试只有自己的成本。 - David Rodríguez - dribeas