1

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.

Andrew Williamson
  • 8,299
  • 3
  • 34
  • 62

1 Answers1

1

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.

the8472
  • 40,999
  • 5
  • 70
  • 122
  • Might be worth noting that the TLAB allocation does already work as efficient as a stack allocation, only needing a pointer bumping in the best case, while already working better than what the OP described, as passing `Foo` to a method does not require copying the object, in fact, even storing a reference to that object into a heap variable does not require such copying. Only if the object survives the next gc, it will be copied. Decomposing into fields after EA just works even better, because it enables subsequent optimizations, treating these fields like local variables. – Holger Nov 15 '17 at 16:18