我做了个试验,试验条件是XP + VS 2005,在Release版本下测试,结果相当令人吃惊。
malloc版本:
#define ITEM_TIMES 1000000
#include <malloc.h>
#define NULL 0
typedef struct UPDATE_ITEM
{
bool down_succeeded;
} *UPDATE_ITEM_PTR;
typedef struct DOWN_ITEM
{
UPDATE_ITEM_PTR update_item;
bool pack;
DOWN_ITEM* next;
} *DOWN_ITEM_PTR;
DOWN_ITEM_PTR create_down_item(bool pack, bool down_succeeded)
{
DOWN_ITEM_PTR down_item = (DOWN_ITEM_PTR) malloc(sizeof(DOWN_ITEM));
down_item->pack = pack;
down_item->update_item = (UPDATE_ITEM_PTR) malloc(sizeof(UPDATE_ITEM));
down_item->update_item->down_succeeded = down_succeeded;
down_item->next = NULL;
return down_item;
}
void free_all_down_item(DOWN_ITEM_PTR root_down_item)
{
DOWN_ITEM_PTR down_item_ptr = root_down_item;
while(down_item_ptr)
{
if(down_item_ptr->update_item)
free(down_item_ptr->update_item);
DOWN_ITEM_PTR temp_ptr = down_item_ptr;
down_item_ptr = down_item_ptr->next;
free(temp_ptr);
}
}
int main()
{
DOWN_ITEM_PTR first, last, ptr;
for(int i = 0; i < ITEM_TIMES; i++)
{
if(i == 0)
{
first = create_down_item(true, false);
last = first;
}
else
{
ptr = create_down_item(true, false);
last->next = ptr;
last = ptr;
}
}
while(1)
;
free_all_down_item(first);
return 0;
}
vector版本:
#include <vector>
using namespace std;
typedef struct UPADTE_ITEM
{
bool down_succeeded;
UPADTE_ITEM()
{
down_succeeded = false;
}
} *UPADTE_ITEM_PTR;
typedef struct DOWN_ITEM
{
UPADTE_ITEM_PTR update_item;
bool pack;
DOWN_ITEM()
{
update_item = NULL;
pack = false;
}
DOWN_ITEM(UPADTE_ITEM_PTR _update_item, bool _pack)
{
update_item = _update_item;
pack = _pack;
}
} *DOWN_ITEM_PTR;
int main()
{
vector<DOWN_ITEM> down_item_vec;
UPADTE_ITEM_PTR update_item_list = new UPADTE_ITEM[ITEM_TIMES];
for(int i = 0; i < ITEM_TIMES; i++)
down_item_vec.push_back(DOWN_ITEM(&update_item_list[i], true));
while(1)
;
delete[] update_item_list;
return 0;
}
改变ITEM_TIMES的值以改变迭代次数。
内存消耗比较:
迭代1000次: malloc - 868k vector - 796K
迭代10000次 : malloc - 1784k vector - 916k
迭代100000次 : malloc - 10956k vector - 2000k
迭代1000000次 : malloc - 102648k vector - 10008k
vector版本内存消耗更少,我想应该是多次malloc导致内存消耗剧增,而vector只在必要的时候才重新分配内存。
而malloc版本在代码中所涉及的指针操作也相当烦琐。
回复 更多评论