今天学习vector的时候在这个网站看到这样一些描述:
按照这个描述,我们使用vector时应尽量一次申请足够的内存,这样能减少其内存分配时间。
于是我做了个试验,想看下内存分配速度提升有多明显,然而试验结果却是 多次内存申请比一次内存申请更节省时间 。测试代码如下:
void test3()
{
auto start = chrono::steady_clock::now();
auto end = chrono::steady_clock::now();
for (int i = 0; i < 5; i++)
{
//申明vector时直接分配内存
start = chrono::steady_clock::now();
vector<StudentInfo> studentinfos(50000);
end = chrono::steady_clock::now();
chrono::duration<double> elapsed_seconds = end - start;
cout << "1 took " << elapsed_seconds.count() << " seconds." << endl;
//使用reserve一次申请50000个元素的内存
start = chrono::steady_clock::now();
vector<StudentInfo> studentinfos2;
studentinfos2.reserve(50000);
end = chrono::steady_clock::now();
elapsed_seconds = end - start;
cout << "2 took " << elapsed_seconds.count() << " seconds." << endl;
//使用reserve五次申请10000个元素的内存
start = chrono::steady_clock::now();
vector<StudentInfo> studentinfos3;
studentinfos3.reserve(10000);
studentinfos3.reserve(10000);
studentinfos3.reserve(10000);
studentinfos3.reserve(10000);
studentinfos3.reserve(10000);
end = chrono::steady_clock::now();
elapsed_seconds = end - start;
cout << "3 took " << elapsed_seconds.count() << " seconds." << endl;
//使用reserve10次申请5000个元素的内存
start = chrono::steady_clock::now();
vector<StudentInfo> studentinfos4;
studentinfos4.reserve(5000);
studentinfos4.reserve(5000);
studentinfos4.reserve(5000);
studentinfos4.reserve(5000);
studentinfos4.reserve(5000);
studentinfos4.reserve(5000);
studentinfos4.reserve(5000);
studentinfos4.reserve(5000);
studentinfos4.reserve(5000);
studentinfos4.reserve(5000);
end = chrono::steady_clock::now();
elapsed_seconds = end - start;
cout << "4 took " << elapsed_seconds.count() << " seconds." << endl << endl;
}
}
代码中分别记录了四种内存申请方式所花费的时间,这四种申请方式分别为:
- 申明vector时直接分配50000个元素的内存
- 先申明vector,再用reserve函数为其1次分配50000个元素的内存
- 先申明vector,再用reserve函数为其分5次分配50000个元素的内存
- 先申明vector,再用reserve函数为其分10次分配50000个元素的内存
下面是运行结果:
可以看到四种分配方式花费的时间依次减少,可见多次分配内存更节省时间。
因此今后使用vector时无需提前进行内存申请,就让后台来自动申请内存,这样代码的运行速度更快。