为什么会有堆栈和堆? [英] Why is there a stack and a heap?

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

问题描述

为什么汇编语言同时使用堆栈和堆?它们似乎是多余的.

Why do assembly languages use both a stack and a heap? They seem redundant.

推荐答案

它们不是多余的.它们每个都有优点和缺点:如果使用得当,堆栈会更快,因为内存分配是微不足道的(推/弹出).缺点是您只能在顶部添加和删除项目(因此,名称,堆栈).另外,总堆栈空间是有限的,并且当用尽时,您会...堆栈溢出.相比之下,堆允许随机分配和释放,您可以在其中存储大量数据,但缺点是分配会带来更多开销-对于每个分配的内存块,必须找到合适的空闲部分,并且在从长远来看,需要避免可用空间的碎片,并且系统必须跟踪可用块的位置.

They're not redundant. Each of them has strengths and weaknesses: A stack is faster if used right, because memory allocation is trivial (push / pop). The downside is that you can only add and remove items at the top (hence the name, stack). Also, total stack space is limited, and when you run out, you have a... well, stack overflow. The heap, by contrast, allows random allocation and deallocation, and you can store large amounts of data there, but the downside is that allocation carries more overhead - for each allocated block of memory, a suitable free portion must be found, and in the long run, fragmentation of the free space needs to be avoided, and the system must track where the free blocks are.

您可以使用堆栈来传递较小的短期值,例如局部计数器变量,函数参数,返回值等;这些适合推式/弹出式分配样式.对于较大或寿命较长的数据结构,请使用堆.

You use the stack to pass around small short-lived values, e.g. local counter variables, function arguments, return values, etc.; these lend themselves to push/pop allocation style. For larger or long-lived data structures, you use the heap.

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

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