C ++中的内存分配区域(堆栈vs堆与静态) [英] Memory allocation areas in C++ (Stack vs heap vs Static)

查看:180
本文介绍了C ++中的内存分配区域(堆栈vs堆与静态)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道C ++中有三个,而不是两个内存区域:堆栈,堆和静态分配的功能的区域。我有两个问题

I understand there are three, not two areas of memory in C++: stack, heap AND the area for static-assigned features. I have two questions


  1. 为什么堆比堆栈慢?

  1. Why is the heap so much slower than the stack? Surely it should just be one extra level of indirection?

分配给静态特征(变量,函数,类)的内存区域提供更快的性能比堆?

Is the area of memory allocated for static "features" (variables, functions, classes) provide faster performance than the heap?


推荐答案

正确的术语是自动的,而不是堆栈,动态而不是堆。另一个是使用C ++ 11现在有四种而不是三种类型的内存。 C ++ 11将线程本地内存添加到组合中。

A couple of side notes first. The correct terminology is automatic rather than stack, dynamic rather than heap. The other is that with C++11 there are now four rather than three types of memory. C++11 adds thread local memory to the mix.

自动内存速度很快,因为它是使用大多数机器上的调用堆栈实现的。所有它需要的是调整堆栈指针的正确数量和瞧!内存已分配。动态内存需要在引擎盖下面做更多的工作。必要的内存可能不会附加到进程,并且要实现这一点需要通过操作系统。即使内存可用,动态内存管理工具仍然必须找到它并将其标记为使用中。

Automatic memory is fast because it is implemented using the call stack on most machines. All it takes is to adjust the stack pointer by the right amount and voila! memory is allocated. Dynamic memory requires a whole lot more work underneath the hood. The requisite memory might not be attached to the process, and getting that to happen requires going through the OS. Even if memory is available, the dynamic memory management tools still have to find it and mark it as in use.

静态内存作为编译的一部分分配和连接过程。当在某些源文件中定义静态变量时,编译代码包含链接器为该变量保留空间的特殊说明。编译器还将C / C ++代码转换为机器码。链接器组合所有这些不同的数据块和代码,并解析地址以形成可执行的二进制映像。运行程序时,该二进制映像将加载到(虚拟)内存中。程序开始执行时,该静态变量的内存就会存在。

Static memory is "allocated" as a part of the compilation and linking process. When you define a static variable in some source file, the compiled code contains special instructions for the linker to reserve space for that variable. The compiler also converts your C/C++ code to machine code. The linker combines all of those different chunks of data and code and resolves addresses to form the executable binary image. When you run your program, that binary image is loaded into (virtual) memory. The memory for that static variable exists as soon as the program starts executing.

至于性能方面,最好不要过于担心性能提前。虽然静态内存速度快,但是有很多缺点。最后你想做的是使你的所有数据静态。

As far as performance is concerned, it's best not to worry too much about performance ahead of time. While static memory is fast, there are lots and lots of drawbacks. The last thing you want to do is to make all of your data static.

这篇关于C ++中的内存分配区域(堆栈vs堆与静态)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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