我们知道JVM存储Class对象,静态变量存储到堆内存位置和局部变量,并调用方法堆栈。 为什么这样?为什么我们不能使用单一内存类型来存储所有内容? 有两种类型的内存位置需要什么,有什么优势?
答案 0 :(得分:1)
关于堆栈的好处是分配和清理是如此快速和简单。这就是为什么它被用于当地人。
当JVM调用一个函数时,它会通过向下移动堆栈指针(或向上移动,无论如何)在堆栈上为函数的本地生成一个空间块。当函数退出时,只需要“清理”堆栈就可以将指针向上移动。非常快,并且不会导致内存分割。
一个略带视觉的例子:
假设我们有这个堆栈
+----------------+ | being used | | being used | | |<-- stack pointer | | | | | | | | +----------------+
然后我们调用一个需要一些本地的函数,所以我们移动堆栈指针并使用堆栈的那部分为本地人:
+----------------+ | being used | | being used | | locals | | locals | | locals | | |<-- stack pointer | | +----------------+
现在功能退出;我们只是将堆栈指针移回:
+----------------+ | being used | | being used |<-- stack pointer | defunct locals | | defunct locals | | defunct locals | | | | | +----------------+
答案 1 :(得分:0)
stack上的分配更便宜,但假设内存以相反的分配顺序释放。
局部变量在方法执行期间存在 - 并且方法以其调用的相反顺序完成执行。因此,使用堆栈来保存局部变量是微不足道的。
对象只要可以访问就会生存,这通常是无法预测的。因此,它们不能(通常)在堆栈上分配。但是,如果JVM可以确定(通过escape analysis)对象没有转义特定的方法调用,则可以将其放在堆栈上。
答案 2 :(得分:0)
When we have a declaration of the form “int a;”:
a variable with identifier “a” and some memory allocated to it is created in the stack.
The attributes of “a” are:
Name: a
Data type: int
Scope: visible only inside the function it is defined, disappears once we exit the
function.
Address: address of the memory location reserved for it.
注意:内存分配在 在初始化之前叠加一个偶数。
Size: typically 4 bytes
Value: Will be set once the variable is initialized
Since the memory allocated for the variable is set in the beginning itself,
we cannot use the stack in cases where the amount of memory required is not known
in advance. This motivates the need for HEAP
The heap segment provides more stable storage of data for a program;
memory allocated in the heap remains in existence for the
duration of a program. Therefore, global variables (storage class
external), and static variables are allocated on the heap.