【c++回顾】杂谈-关于vector的内存分配速度

今天学习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;
	}
}

代码中分别记录了四种内存申请方式所花费的时间,这四种申请方式分别为:

  1. 申明vector时直接分配50000个元素的内存
  2. 先申明vector,再用reserve函数为其1次分配50000个元素的内存
  3. 先申明vector,再用reserve函数为其分5次分配50000个元素的内存
  4. 先申明vector,再用reserve函数为其分10次分配50000个元素的内存

下面是运行结果:

在这里插入图片描述
可以看到四种分配方式花费的时间依次减少,可见多次分配内存更节省时间。
因此今后使用vector时无需提前进行内存申请,就让后台来自动申请内存,这样代码的运行速度更快。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值