为什么堆上的内存分配比栈上慢得多? [英] Why is memory allocation on heap MUCH slower than on stack?

查看:22
本文介绍了为什么堆上的内存分配比栈上慢得多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经被告知很多次了.但我不知道为什么......从堆分配内存时涉及哪些额外成本?和硬件有关吗?它与CPU周期有关吗?这么多的猜测,但没有确切的答案......有人可以给我一些详细说明吗?

I have been told this many times. But I don't know WHY...What extra cost is involved when allocating memory from heap? Is it hardware related? Is it related to CPU cycles? So many guesses but no exact answers...Could someone give me some elaboration?

正如unwind"所说,Heap 数据结构比 Stack 更复杂.在我看来,当线程开始运行时,一些内存空间作为它的堆栈分配给线程,而堆由进程内的所有线程共享.这种范式需要一些额外的机制来管理每个线程对共享堆的使用,例如垃圾收集.我说的对吗?

Just as "unwind" said, the Heap data structure is more complicated than Stack. And In my opinion, some memory space is allocated to a thread as its Stack when it starts to run, while the heap is shared by all the threads within a process. This paradigm require some extra mechanism to manage each thread's usage of the shared heap, such as Garbage Collection. Am I right on this?

推荐答案

因为堆是比栈复杂得多的数据结构.

Because the heap is a far more complicated data structure than the stack.

对于许多架构,在堆栈上分配内存只是改变堆栈指针的问题,即它是一条指令.在堆上分配内存包括寻找足够大的块、拆分它,以及管理允许像 free() 这样的东西以不同顺序执行的簿记".

For many architectures, allocating memory on the stack is just a matter of changing the stack pointer, i.e. it's one instruction. Allocating memory on the heap involves looking for a big enough block, splitting it, and managing the "book-keeping" that allows things like free() in a different order.

保证在范围(通常是函数)退出时释放在堆栈上分配的内存,并且不能只释放其中的一部分.

Memory allocated on the stack is guaranteed to be deallocated when the scope (typically the function) exits, and it's not possible to deallocate just some of it.

这篇关于为什么堆上的内存分配比栈上慢得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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