demo
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Point
{
float x, y, z;
Point():x(0.0), y(0.0), z(0.0){}
};
int main (int argc, char** argv)
{
const int num = 5000000;
/ test vector perfermance when add element ///
/* demo0 */
clock_t t0 = clock();
vector<Point> points1;
for (int i = 0; i < num; i++)
{
points1.push_back(Point());
}
clock_t t1 = clock();
cout<<"push_back directly cost time : "<<(t1-t0)/1000<<"[ms]"<<endl;
/* demo1 */
vector<Point> points2;
points2.reserve(num);
for (int i = 0; i < num; i++)
{
points2.push_back(Point());
}
clock_t t2 = clock();
cout<<"push_back after reserve cost time : "<<(t2-t1)/1000<<"[ms]"<<endl;
/// test vector perfermance when copy element /
/* demo2 */
clock_t t3 = clock();
vector<Point> points3 = points2;
clock_t t4 = clock();
cout<<"copy directly cost time : "<<(t4-t3)/1000<<"[ms]"<<endl;
/* demo3 */
vector<Point> points4;
points4.resize(points2.size());
copy(points2.begin(), points2.end(), points4.begin());
clock_t t5 = clock();
cout<<"use copy function cost time : "<<(t5-t4)/1000<<"[ms]"<<endl;
return 0;
}
result:
push_back directly cost time : 155[ms]
push_back after reserve cost time : 75[ms]
copy directly cost time : 76[ms]
use copy function cost time : 55[ms]
分析
从demo0和demo1的测试结果来看,demo1的效率明显高于demo0,差异在于demo0是在添加元素的过程中分配内存,因此决定了demo0的方式在添加元素过程中要不断的新分配内存用来存储新元素,存在不断分配内存的过程.而demo1就只在初始化的时候分配过一次内存,后面的push_back更多的就像是在复制,所以效率较高.
从demo2和demo3的测试结果来看,demo3使用算法函数copy()实现了更高效率的复制过程,为什么会有这么高的效率可参考https://en.cppreference.com/w/cpp/algorithm/copy,在对于trival assignment等操作可以直接调用c函数(memmove和memcpy)进行内存的拷贝,而且还有一些其它的优化.
结论
1. 在对vector容器进行元素的添加时,如果在容器容量已知的情况下,可先reserve分配内存,然后在添加,能有效提高效率
2. 在对vector容器进行拷贝时,调用算法库中的copy()函数效率会比直接拷贝高