简体   繁体   English

为什么在Java中使用堆来管理对象引用?

[英]Why heaps are used for managing object references in java?

Functions and variables are stored on stack while string and object references are stored on heap. 函数和变量存储在堆栈中,而字符串和对象引用存储在堆中。 Why is there a difference on how they are stored? 为什么它们的存储方式有所不同?

Some of the comments above offer links to the difference. 上面的一些评论提供了区别的链接。 The stack is temporary. 堆栈是临时的。 Chunks of the stack are used as your code nests. 堆栈块用作代码嵌套。 Think of a big chunk of memory in which you keep track only of the very top of the memory. 想想很大的内存块,您只在其中跟踪内存的最高端。 When you call a method, the system knows how much memory is required to remember where to return to when the method exits and enough space for the variables required for the method. 当您调用一个方法时,系统会知道需要多少内存来记住该方法退出时返回到的位置以及足够的空间来存储该方法所需的变量。 The stack pointer then points higher up in memory, giving you all the space it just skipped over. 然后,堆栈指针指向内存中的较高位置,为您提供它刚刚跳过的所有空间。 When your method returns, the stack pointer is returned to where it was before your method was called. 当方法返回时,堆栈指针将返回到调用方法之前的位置。 Any variables that were there are now gone. 现在所有存在的变量都消失了。

It's not entirely that simple in a complex world like Java, but I still think of the stack in assembly language, which is where I first encountered it. 在像Java这样的复杂世界中,这并不完全简单,但是我仍然想到了汇编语言中的堆栈,这是我第一次遇到它的地方。 (I'm old.) Close enough for this discussion. (我已经老了。)

The heap is different. 堆是不同的。 The heap is managed memory with complex structures that keep track of the memory you've used. 堆是具有复杂结构的托管内存,可以跟踪您使用的内存。 If you say new Foo(), Java knows how big a Foo is and it asks the heap for enough space to hold one. 如果您说new Foo(),则Java知道Foo有多大,并要求堆提供足够的空间来容纳一个Foo。 Much more complex things happen around managing that. 管理它会发生许多更复杂的事情。 But when your method returns, that object still exists. 但是,当您的方法返回时,该对象仍然存在。 If it were allocated on the stack, there'd be real problems, because the stack unwinds when your method returns. 如果它是在堆栈上分配的,那将是真正的问题,因为当您的方法返回时,堆栈会展开。 But your memory in the heap is still allocated, and your object can continue to exist. 但是堆中的内存仍已分配,并且对象可以继续存在。

Again, it's not that simple, but maybe it makes sense. 同样,它不是那么简单,但是也许是有道理的。

Space on the stack exists only as long as your method is running. 堆栈空间仅在您的方法运行时才存在。 (I presume if you nest inside {}, it might allocate more space. I don't know.) Space on the heap persists until objects are freed, but that can be far longer than the duration of a method call. (我猜想如果您嵌套在{}中,它可能会分配更多的空间。我不知道。)堆上的空间一直存在,直到对象被释放为止,但这可能比方法调用的持续时间更长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM