Reputation: 8661
Say I have a value type Foo
, and a method Bar
which accepts a reference to a Foo
. Most languages will allow me to allocate a new Foo
on the stack, and will automatically box it when I try and pass it in to Bar
. However, as far as I am aware, this involves copying the Foo
value onto the heap, and then using that reference.
Is it possible for a language to include a way of allocating a garbage collected object on the stack? When the method ends, the runtime could check if the object is still in use, and only then would it need to allocate the object on the heap, and update the references.
I imagine this would improve performance for methods that do not keep the reference, and it would hinder performance for methods that do.
Upvotes: 1
Views: 65
Reputation: 43052
Yes, Graal's partial escape analysis does that. While regular EA can only stack-allocate (more precisely: decompose into fields, put fields onto stack) when the object doesn't escape partial EA can optimistically allocate on the stack and only reify the data into an object on uncommon cases where the object must exist.
Also note that garbage collection is not a binary choice. You can have environments that mix and match garbage-collection, ref-counting, arena or scope-based allocators with automatic deallocation and completely manual management. In such a case stack allocations could also be one of the latter things while some heap would be garbage-collected.
Upvotes: 1