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

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

问题描述

我被告知过很多次了.但我不知道为什么......从堆分配内存时会涉及哪些额外成本?和硬件有关吗?它与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天全站免登陆