Which is faster: Stack allocation or Heap allocation(哪个更快:堆栈分配或堆分配)
问题描述
这个问题可能听起来很初级,但这是我与另一位与我合作的开发人员进行的辩论.
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.
这篇关于哪个更快:堆栈分配或堆分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:哪个更快:堆栈分配或堆分配
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
