您的位置:首页 > 其它

STL中使用reserve()提升效率

2015-06-04 11:07 218 查看
前言:我们使用STL容器的时候,它们能够自动进行容量扩充,所以在一定程度上,我们是不需要去考虑它们的资源分配的。

需要注意的有两点:

1、当我们知道容器中存放元素的大致数量时,可以通过reserve()方法减少系统对容器进行资源再分配的次数;

2、当我们能够确定容器中存放元素的最大数量后,可以通过reserve()修剪超额资源,减少不必要开销

关于第一点,首先来看个例子:

vector<int> vInt;
vInt.push_back (99);
for (int i = 0; i != 1000; ++i) {
vInt.push_back (i);
}


这样也许不能够看出来很大的问题,那么我们添加点东西:

vector<int> vInt;
vInt.push_back (99);
int* p = &vInt[0];
int reallcTime = 0;
for (int i = 0; i != 1000; ++i) {
vInt.push_back (i);
if (p != &vInt[0]) {
reallcTime++;
cout << "Reallocate times: " << reallcTime << endl;
cout << "&vInt[0]   now:   " << &vInt[0] << endl;
p = &vInt[0];
}
}


 

output:

Reallocate times: 1

&vInt[0]   now:   003F66E0

Reallocate times: 2

&vInt[0]   now:   003F67C0

Reallocate times: 3

&vInt[0]   now:   003F6808

Reallocate times: 4

&vInt[0]   now:   003F6A30

Reallocate times: 5

&vInt[0]   now:   003F67C0

Reallocate times: 6

&vInt[0]   now:   003F6820

Reallocate times: 7

&vInt[0]   now:   003F6A30

Reallocate times: 8

&vInt[0]   now:   003F67C0

Reallocate times: 9

&vInt[0]   now:   003F6A30

Reallocate times: 10

&vInt[0]   now:   003F6B18

Reallocate times: 11

&vInt[0]   now:   003F6C50

Reallocate times: 12

&vInt[0]   now:   003F6E08

Reallocate times: 13

&vInt[0]   now:   003F6A30

Reallocate times: 14

&vInt[0]   now:   003F6DB8

Reallocate times: 15

&vInt[0]   now:   003F72E8

Reallocate times: 16

&vInt[0]   now:   003F7A90

Reallocate times: 17

这下看出来了吧,在往vInt这个容器中添加1000个数据时,它的首地址变了17次(即容器17次被重新分配内存),这时候我们添加一行数据:

vector<int> vInt;
vInt.push_back (99);
vInt.reserve (1001);  // 添加的一行
int* p = &vInt[0];
int reallcTime = 0;
for (int i = 0; i != 1000; ++i) {
vInt.push_back (i);
if (p != &vInt[0]) {
reallcTime++;
cout << "Reallocate times: " << reallcTime << endl;
cout << "&vInt[0]   now:   " << &vInt[0] << endl;
p = &vInt[0];
}
}
output:


 

这时候,完全没有内存再分配了,仅仅只是在调用reserve()的时候会分配一次,1000个数据,省下了16次容器内存分配。

关于第二点,这个很好理解:容器中元素的数量不超过某个值,那就别把容器弄的太大,多了就是浪费!

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: