为什么堆栈存储器“便宜"?比堆内存在C? [英] Why is stack memory "cheaper" than heap memory in C?

查看:96
本文介绍了为什么堆栈存储器“便宜"?比堆内存在C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比较以下两个:

int arr[10]; // stack memory
int* x = malloc(sizeof(int)*10); // heap memory

两者实际上都分配了10个整数变量.但是,我们经常说第一个b/c便宜得多(分配和取消分配更快),它只是将栈指针移到了前面.

Both are essentially allocating 10 integer variables. However, we often say that the first one is much cheaper (faster to alloc and dealloc) b/c it simply moves ahead the stack pointer.

我们知道所有程序都在虚拟内存空间中运行,并且仅分配程序实际使用的部分(也称为映射到物理内存),而未使用的部分则保持虚拟状态.这就是操作系统在不同程序之间共享物理内存的方式.

We know that all programs run in virtual memory space, and only the portion that a program actually uses will be allocated (aka mapped to physical memory), and unused ones stay virtual. And that's how the OS shares physical memory between different programs.

所以我的问题来了.在我看来,无论您如何分配内存(在堆栈上还是在堆上),一个共同点是操作系统需要找到&保留物理内存块,并将虚拟内存地址(无论是在堆栈上还是在堆上)映射到物理地址.当系统需要删除映射&时,解除分配也是如此.释放物理内存.那为什么堆栈分配/解除分配更快呢?两者之间最大的内存分配开销似乎很合理.

So here comes my question. It seems to me that no matter how you allocate the memory (on stack or on heap), one thing in common is that the OS needs to find & reserve a physical memory block, and map the virtual memory address, whether its on stack or on heap, to the physical address. The same for deallocation, when the system needs to remove the mapping & free the physical memory. Then why is stack allocation/deallocation faster? The biggest overhead in memory allocation seems pretty fair between the two.

推荐答案

mallocfree的调用通常平均需要几百到几千条指令,具体取决于实现方式,堆和其他详细信息.

Calls to malloc and free typically require somewhere between a few 100's and a few 1,000's of instructions on average depending on implementation, current fragmentation of the heap, and other details.

为一个函数分配和取消分配堆栈帧需要大约4条指令.

Allocating and deallocating the stack frame for a function requires on the order of 4 instructions.

这篇关于为什么堆栈存储器“便宜"?比堆内存在C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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