其中更快:堆栈分配或堆分配 [英] Which is faster: Stack allocation or Heap allocation

查看:146
本文介绍了其中更快:堆栈分配或堆分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题可能听起来很小,但这是我与另一个与我合作的开发人员的辩论。

This question may sound fairly elementary, but this is a debate I had with another developer I work with.

我正在照顾堆栈分配的东西,而不是堆分配它们。他正在跟我说话,看着我的肩膀,并评论说没有必要,因为他们是同样的表现聪明。

I was taking care to stack allocate things where I could, instead of heap allocating them. He was talking to me and watching over my shoulder and commented that it wasn't necessary because they are the same performance wise.

我总是有一种印象,堆栈是恒定时间,堆分配的性能取决于当前的堆分配(找到一个合适的大小的洞)和解除分配(崩溃空洞减少碎片,因为许多标准库实现需要时间做这个分配)在删除期间,如果我没有错误)。

I was always under the impression that growing the stack was constant time, and heap allocation's performance depended on the current complexity of the heap for both allocation (finding a hole of the proper size) and de-allocating (collapsing holes to reduce fragmentation, as many standard library implementations take time to do this during deletes if I am not mistaken).

这打击了我可能是非常依赖于编译器。对于这个项目,我使用的是 Metrowerks 编译器,用于 PPC 架构。洞察这种组合将是最有帮助的,但一般来说,对于GCC和MSVC ++,是什么情况?堆分配的性能不如堆栈分配的高吗?是没有区别的?

This strikes me as something that would probably be very compiler dependent. For this project in particular I am using a Metrowerks compiler for the PPC architecture. Insight on this combination would be most helpful, but in general, for GCC, and MSVC++, what is the case? Is heap allocation not as high performing as stack allocation? Is there no difference? Or are the differences so minute it becomes pointless micro-optimization.

推荐答案

堆栈分配要快得多,因为它确实是移动堆栈指针。
使用内存池,您可以从堆分配中获得可比的性能,但是带有稍微增加的复杂性和自己的头痛。

Stack allocation is much faster since all it really does is move the stack pointer. Using memory pools, you can get comparable performance out of heap allocation, but that comes with a slight added complexity and its own headaches.

此外,堆栈与堆不仅是一个性能考虑;它也告诉你很多关于对象的预期寿命。

Also, stack vs. heap is not only a performance consideration; it also tells you a lot about the expected lifetime of objects.

这篇关于其中更快:堆栈分配或堆分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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