C++ std::allocator<T> 与new对比效率使用

本文对比了C++中使用new与allocator进行内存分配及初始化的速度差异。通过实验展示allocator如何通过分离分配与初始化过程来提高效率。

基础知识通道:http://blog.youkuaiyun.com/Xiejingfa/article/details/50955295

 

C/C++:

 

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 
 5 #define allocate_length 100000
 6 
 7 
 8 int main()
 9 {
10 
11     //allocator比new快的原因:分离分配和初始化这两个操作allocator少执行一步,new则一般执行两次(初始化和赋值);
12 
13 
14     std::clock_t start = 0, end = 0;
15 
16     start = clock();
17     std::string *str1 = new std::string[allocate_length];
18     auto str6=str1;
19     for (int i = 0; i < allocate_length; i++)
20     {
21         *str1++ = "Hello World";
22     }
23 
24     delete []str6;
25     end = clock();
26     std::cout << (double(end - start) / CLOCKS_PER_SEC) << std::endl;
27 
28 
29 
30 
31     start = clock();
32     std::allocator<std::string> str_allocate;
33     std::string *str3 = str_allocate.allocate(allocate_length); //分配20个string原始内存
34     auto str4=str3;
35 
36     //方法一:使用默认构造
37     for (int i = 0; i < allocate_length; i++)
38     {
39         str_allocate.construct(str3++,"Hello World");
40     }
41 
42     //方法二:使用allocator的伴随算法(分别是带n与不带)
43     //其他算法:std::uninitialized_copy(iterator begin,iterator end,T value);
44 
45     //std::uninitialized_fill_n(str3,allocate_length,"Hello World");
46 
47 
48     //str_allocate.destroy()调用对象的析构,但是内存还是由allocator控制,需要自己释放
49     str_allocate.deallocate(str4,allocate_length);
50     end = clock();
51 
52     std::cout << (double(end - start) / CLOCKS_PER_SEC) << std::endl;
53 
54 
55     return 0;
56 }

 

转载于:https://www.cnblogs.com/xuaidongstdudyrecording/p/7142353.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值