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

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

问题描述

这个问题可能听起来很初级,但这是我与另一位与我合作的开发人员进行的辩论.

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).

这让我印象深刻,因为它可能非常依赖编译器.对于这个项目,我正在为 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天全站免登陆