我之前释放内存时 malloc 更快吗 [英] Is malloc faster when I freed memory before

查看:51
本文介绍了我之前释放内存时 malloc 更快吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我分配和释放内存,然后我分配最大大小的内存作为先前释放的部分.

When I allocate and free memory and afterwards I allocate memory that is max the size as the previously freed part.

第二次分配会比第一次更快吗?

May the 2nd allocation be faster than the first?

也许是因为它已经知道一个空闲的内存区域?还是因为这部分堆仍然分配给进程?还有其他可能的优势吗?

Maybe because it already knows a memory region that is free? Or because this part of the heap is still assigned to the process? Are there other possible advantages?

或者它通常没有区别?

如评论中所问:

  • 我对 gcc 和 MSVC 特别感兴趣.
  • 我的假设是之前操作系统没有赎回"内存.

由于有很多关于实施的具体细节,我想更清楚地说明,这是一个假设性问题.我不打算滥用它,但我只想知道这是否可能发生,以及假设加速的原因是什么.

As there is a lot going about specific details about implementation, I'd like to make it more clear, that this is a hypothetical question. I don't intend to abuse this, but I just want to know IF this may occur and what the reasons for the hypothetical speedup might be.

推荐答案

在 GCC x86_64 等一些常见平台上,有两种 malloc():传统的小分配类型,以及mmap 种类为大的.基于 mmap 的大型分配将具有较少的相互依赖性.但是在某些情况下,传统的小程序确实会在某些情况下体验很大的加速,因为之前已经free()'d 了内存.

On some common platforms like GCC x86_64, there are two kinds of malloc(): the traditional kind for small allocations, and the mmap kind for large ones. Large, mmap-based allocations will have less interdependence. But traditional small ones will indeed experience a big speedup in some cases when memory has previously been free()'d.

这是因为正如您所建议的,free() 不会立即将内存返回给操作系统.实际上它通常不能这样做,因为内存可能位于连续的堆的中间.因此,在许多系统(但不是全部)上,malloc() 只会在需要向操作系统请求更多堆空间时才会变慢.

This is because as you suggest, free() does not instantly return memory to the OS. Indeed it cannot do so in general, because the memory might be in the middle of the heap which is contiguous. So on lots of systems (but not all), malloc() will only be slow when it needs to ask the OS for more heap space.

这篇关于我之前释放内存时 malloc 更快吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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