Why do Objects live on heap & not variables & reference variables?
Memory hierarchies in the computing world(e.g.register, cache, Ram , disk etc) exist because of efficiency.
Heap and
stack are data structures with different characteristics
The heap is memory used for dynamic allocation; means that you can allocate and/or free a block at any time, In a heap that great flexibility has a price that is: it's much more complex to keep track of which parts of the heap are allocated or free at any given time. Unlike the stack, there's no a LIFO schema to the allocate/deallocate blocks from the heap. In other words the heap is way slower than the stack(it's trivial to allocate/deallocate memory theret ,a pointer/integer is simply incremented or decremented)
Another efficiency problem is that heap, is generally a global resource, so is faced to guaranties the safety in a multi-threading environment, i.e. each allocation and deallocation needs to be synchronized with the rest of threads that accesses the heap.
For each
thread correspond a stack, while there's typically only one heap for the entire application. Anyway here can be multiple heaps too for different types of allocation for example.
Objects are dynamic things can be very complex and have longer life than e.g. methods so they're posed in heap that can grow at will . Stacks on the other hand tend to be smaller and faster so more appropriate to contain e.g.primitive data or data that have to reused frequently at a faster rate than in heap
Cheers
Harry G.T. Kar