为什么内存分配堆远远超过堆栈慢? [英] Why is memory allocation on heap MUCH slower than on stack?

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

问题描述

有人告诉我很多次。但我不知道为什么...什么从堆中分配内存时需要支付额外费用涉及?它是硬件相关的?这是否与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?

就像开卷之称,堆数据结构比堆栈更复杂。而在我看来,一些内存空间分配给一个线程作为它的堆栈时,它开始运行,而堆是由一个进程内的所有线程共享。这种模式需要一些额外的机制来管理共享堆的每个线程的使用,比如垃圾收集。我说的对这个?

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.

许多体系,在栈上分配内存仅仅是一个改变堆栈指针的事,即它是一个指令。在堆中分配的内存包括寻找一个足够大的块,拆分它,并管理簿记,允许像免费的东西()以不同的顺序。

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天全站免登陆