• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why are objects created on the HEAP compared to the STACK ?  RSS feed

 
dhruve ashar
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Off lately i am not able to get to a conclusion as to why objects are created on the heap as compared to the stack . The question is not streamlined to a specific language/platform. In C++ objects are created on the stack while in Java and C# objects are created on the heap.

I could draw the following points, but yet not reach to a convincing conclusion.

1. Dynamic allocation and deallocation of memory can take place on the stack as well.

2. As far as the activation record or the stack frame is concerned, all the static information like the return address, context switch info, temperories, arguments passed, etc can be stored at the bottom of the stack frame while space for local variables/objects which can change dynamically can be on the top of the stack, thereby allowing the stack to shrink or grow without affecting any other information. So if at compile time we dont have the information of the size and length of data structure we can place it on the top of the stack.

3. For static fields we have a global area in memory.

In search for a convincing answer.... Thanks in advance
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all the following difference between Java and C++ is important: in Java, variables of non-primitive types are references to objects, whereas in C++, variables can represent objects themselves.

Local variables (declared inside methods) in both Java and C++ are allocated on the stack. The reason for doing this is that they can then be cleaned up "for free" when the method returns (by unwinding the stack).

In C++, since variables represent objects themselves, if you create local variables, objects are allocated on the stack. In Java, the variable is not the object itself, but only a reference (almost the same thing as a pointer) to the object. The object itself, which the variable refers to, is allocated on the heap. The garbage collector will automatically cleanup objects on the heap if there are no references to the object anymore in live code.

That's just how Java is defined to work. Java provides no way to explicitly allocate objects on the stack.

And then now for the advanced stuff:

Sun's JVM does a lot of sophisticated optimizations, one of which is escape analysis. What this means is that the JVM investigates the code of a method, and if it detects an object being used as a temporary variable, which doesn't escape the scope of the method, it might allocate the object on the stack instead of the heap. That's more efficient: the object can be cleaned up immediately for free when the method ends; the garbage collector doesn't have to bother with it.

Escape analysis was added in JDK 6 update 14 as an experimental feature. Unfortunately it has been disabled again since JDK 6 update 18 (probably it wasn't always working correctly); it will be available again in a future JDK 6 update.
 
dhruve ashar
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Jesper Young
What i am looking for is the need of allocation on HEAP region??? The points listed indicate the possible reason for shifting the allocation on heap, but all of them can be easily satisfied with a stack. So the doubt still remains as to why heap is chosen over stack!
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
dhruve ashar wrote: So the doubt still remains as to why heap is chosen over stack!



I think the question should be reversed... Why objects are even allowed on the stack with C++? Stacks are thread local. They generally have a size of only about a megabyte or so -- sometimes configured even smaller to allow more threads. Why would any language designer make it so ridiculously easy to overflow the stack?

Henry
 
dhruve ashar
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for responding, but i am looking for a conclusion and not factual content. I want to know the reason which forces us to opt for a heap or the reason where the stack fails to provide for object management. If everything can be done on the stack why do we need a heap? In short, i need a contrast of why "object creation on HEAP" vs "object creation on STACK".
 
fred rosenberger
lowercase baba
Bartender
Posts: 12565
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Everything cannot be done on the stack - or perhaps, it cannot be done efficiently on the stack...

Let's assume I create a new object, and per your idea, we create it on the stack. Just before I exit my method, I want to return this new object to the caller. How would I do that?

If the object is in the heap, I simply return it's memory address.

However, if it's in the stack, it gets complicated...because when the method exits, the stack pointer drops back down to the calling method's frame. That effectively means that the object I created in the higher frame is now fair game - it can (and will) be blown away as the stack pointer moves up again for other method calls. I'd have to make a temporary copy of the object, and somehow insert it into the caller's frame, wasting time, CPU cycles, etc.

 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The lifespan of a JVM stack variable (or object?) is defined to be the duration of a
code block. When a code block completes, its portion of the stack is instantly ready
for reuse; no nulling, collecting/defragmenting or returning memory to a pool. Just
move the stack pointer and continue. A stack is the ideal structure.

On the other hand, the price of object persistence on the heap is much higher. When
is an object, or its island, no longer reachable? Garbage collection is the process of
scraping together dead memory fragments into usable chunks. Since this cannot be
terribly efficient, the garbage collector must run during program down time.

If persistent storage were put on the stack, it would no longer be a stack. By definition,
a stack is LIFO storage (last in, first out). This LIFO behavior is behind the stack attributes
described above. There is nothing at all LIFO about managing persistent object storage.
So bottom line, stack behavior does not offer any advantage over a heap for persistent
object storage.

Jim ... ...
 
dhruve ashar
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Jim
What do you exactly mean by "persistent storage were put on the stack"? If an object has to be made persistent, it is state is written to a non volatile memory and during execution if you want the object back, there is always a scope as the local members and temporaries are placed on the top of the stack frame for that particular method.
 
Jim Hoglund
Ranch Hand
Posts: 525
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dhruve : Reading the entire post, you will see a proposal to use a stack data structure
for storing object state. My comment is to point out that because objects persist for an
uncertain time period, storing their state in a stack does not make sense. Does this help?

Jim ... ...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!