一个大的 malloc 与多个较小的重新分配

发布于 2024-09-28 23:21:47 字数 233 浏览 1 评论 0原文

抱歉,如果之前有人问过这个问题,我无法找到我想要的东西。

我正在从列表中读取字段并将它们写入内存块。我可以

  • 遍历整个列表,找到所需的总大小,执行一次 malloc,然后再次遍历列表并复制每个字段;
  • 当我写入值时,遍历整个列表并重新分配内存块;

现在,第一个对我来说似乎是最有效的(调用次数最少)。这两种方法的优点和缺点是什么?

感谢您抽出时间。

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

  • 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 ?

Thank you for your time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夜巴黎 2024-10-05 23:21:47

第一种方法几乎总是更好。 realloc() 通常通过将内存块的全部内容复制到新分配的较大块中来工作。因此,n 次重新分配可能意味着 n 个副本,每个副本都比前一个大。 (如果每次向分配中添加 m 字节,则第一个重新分配必须复制 m 字节,下一个 2m,下一个 3m,...)。

迂腐的答案是 realloc() 的内部性能影响是特定于实现的,不是由标准明确定义的,在某些实现中,它可以通过立即移动字节的魔法精灵来工作,等等等等 - 但在任何实际的实现中,realloc()表示复制。

The first approach is almost always better. A realloc() typically works by copying the entire contents of a memory block into the freshly allocated, larger block. So n reallocs can mean n copies, each one larger than the last. (If you are adding m bytes to your allocation each time, then the first realloc has to copy m bytes, the next one 2m, the next 3m, ...).

The pedantic answer would be that the internal performance implications of realloc() are implementation specific, not explicitly defined by the standard, in some implementation it could work by magic fairies that move the bytes around instantly, etc etc etc - but in any realistic implementation, realloc() means a copy.

还给你自由 2024-10-05 23:21:47

根据您认为最有可能的最大值,您可能最好最初分配相当数量的空间。

然后,如果您发现需要更多空间,不要只是为额外的空间分配足够的空间,而是额外分配一大块空间。

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

举例来说,最初分配 100K。如果您随后发现需要更多,请重新分配到 200K,即使您只需要 101K。

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.

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

眼眸里的那抹悲凉 2024-10-05 23:21:47

不要重新发明轮子并使用 CCAN 的 darray ,它实现了类似于 paxdiablo 描述的方法。请参阅 GitHub 上的 darray

Don't reinvent the wheel and use CCAN's darray which implements an approach similar to what paxdiablo described. See darray on GitHub

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文