C++ STL内存池的效果

<pre name="code" class="cpp">#include<vector>
#include<sys/time.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
    class A{
        public:
        A(){
            a=3;
        }
        private:
        int a;
    };
int main()
{
    struct timeval pre;
    struct timeval now;
    vector<A> v;
    vector<A*> vp;
    gettimeofday(&pre, 0);
    
    for(int i = 0; i < 1000000; i++)    
    {
        A ca;
        v.push_back(ca);
    }
    gettimeofday(&now, 0);
    unsigned long tv =( now.tv_sec*1000000 + now.tv_usec \
                          - pre.tv_sec*1000000 - pre.tv_usec);
    cout<<tv<<endl;
    gettimeofday(&pre, 0);
    for(int i = 0; i<1000000; i++)
    {
        vp.push_back(new A());
    }
    gettimeofday(&now, 0);
    tv =( now.tv_sec*1000000 + now.tv_usec \
                          - pre.tv_sec*1000000 - pre.tv_usec);
    cout<<tv<<endl;
}


21603
70920

1. 因为STL内存池的使用, 提高了效率。

</pre></p>
#include<vector>
#include<sys/time.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
    class A{
        public:
        A(){
            a=3;
        }
        private:
        int a;
       <span style="color:#cc0000;"> int b[1000];--------------------------------------------------------------------</span>
    };
int main()
{
    struct timeval pre;
    struct timeval now;
    vector<A> v;
    vector<A*> vp;
    gettimeofday(&pre, 0);
    
    for(int i = 0; i <<span style="color:#cc0000;"> 100</span>; i++)    <span style="background-color: rgb(255, 255, 255);"><span style="color:#cc0000;">-----------------------------------------------</span></span>
    {
        A ca;
        v.push_back(ca);
    }
    gettimeofday(&now, 0);
    unsigned long tv =( now.tv_sec*1000000 + now.tv_usec \
                          - pre.tv_sec*1000000 - pre.tv_usec);
    cout<<tv<<endl;
    gettimeofday(&pre, 0);
    for(int i = 0; i<100; i++)
    {
        vp.push_back(new A());
    }
    gettimeofday(&now, 0);
    tv =( now.tv_sec*1000000 + now.tv_usec \
                          - pre.tv_sec*1000000 - pre.tv_usec);
    cout<<tv<<endl;
}

462
64

2. 因为vector的push_back函数需要拷贝输入变量,当输入变量体积大时,此函数造成整体效率较低。


总结:STL中容器使用到了内存池,增加成员时从内存的角度STL做了两件事:1. 从内存池中分配内存,2. 拷贝输入变量值。

当输入变量体积大时,拷贝成为拖累。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值