一个大的malloc与多个较小reallocs [英] One large malloc versus multiple smaller reallocs

查看:128
本文介绍了一个大的malloc与多个较小reallocs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这已被问过,我一直没能找到正是我所期待的。

Sorry if this has been asked before, I haven't been able to find just what I am looking for.

我从列表中读取域并将其写入到一个内存块。我可以

I am reading fields from a list and writing them to a block of memory. I could


  • 走在整个列表中,找到所需的总规模,做一的malloc ,然后再次走列表,并复制每个字段;

  • 步行整个名单和的realloc 的记忆,我写的价值观块;

  • Walk the whole list, find the total needed size, do one malloc and THEN walk the list again and copy each field;
  • Walk the whole list and realloc the block of memory as I write the values;

眼下的第一个似乎是最有效的给我(电话编号最小的)。什么是这两种方法的优点和缺点是什么?

Right now the first seems the most efficient to me (smallest number of calls). What are the pros and cons of either approach ?

感谢您的时间。

推荐答案

你可能会更好过最初分配的空间像样的数目的基础上,你认为是最有可能的最大值。

You're probably better off allocating a decent amount of space initially, based on what you think is the most likely maximum.

然后,如果你发现你需要更多的空间,不要只分配足够的额外,分配一大块额外的费用。

Then, if you find you need more space, don't just allocate enough for the extra, allocate a big chunk extra.

这将最大限度地减少重新分配的数量,同时仍然只处理列表一次。

This will minimise the number of re-allocations while still only processing the list once.

举例来说,最初分配100K。如果然后找到你需要更多的,重新分配到200K,即使你只需要101K。

By way of example, initially allocate 100K. If you then find you need more, re-allocate to 200K, even if you only need 101K.

这篇关于一个大的malloc与多个较小reallocs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆