<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. 拷贝输入变量值。
当输入变量体积大时,拷贝成为拖累。