C++ allocator与new对比效率使用

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

#include <iostream>
#include <vector>
#include <string>

#define allocate_length 100000


int main()
{
    //allocator比new快的原因:分离分配和初始化这两个操作allocator少执行一步,new则一般执行两次(初始化和赋值);
    std::clock_t start = 0, end = 0;

    start = clock();
    std::string *str1 = new std::string[allocate_length];
    auto str6=str1;
    for (int i = 0; i < allocate_length; i++)
    {
        *str1++ = "Hello World";
    }

    delete []str6;
    end = clock();
    std::cout << (double(end - start) / CLOCKS_PER_SEC) << std::endl;



    start = clock();
    std::allocator<std::string> str_allocate;
    std::string *str3 = str_allocate.allocate(allocate_length); //分配20个string原始内存
    auto str4=str3;

    //方法一:使用默认构造
    for (int i = 0; i < allocate_length; i++)
    {
        str_allocate.construct(str3++,"Hello World");
    }

    //方法二:使用allocator的伴随算法(分别是带n与不带)
    //其他算法:std::uninitialized_copy(iterator begin,iterator end,T value);

    //std::uninitialized_fill_n(str3,allocate_length,"Hello World");


    //str_allocate.destroy()调用对象的析构,但是内存还是由allocator控制,需要自己释放
    str_allocate.deallocate(str4,allocate_length);
    end = clock();
    std::cout << (double(end - start) / CLOCKS_PER_SEC) << std::endl;


    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值