0

So I'm relatively new to Java, and just read this really interesting Wikipedia article about escape analysis. However, the only time it mentions that stack allocation is used is when the object does not escape the method call. This seems somewhat limited; but then again, I can't think of any other time I would want an object allocated to the stack. So I'm wondering:

1) Is there any other time that it would make sense for an object to be allocated to the stack?
2) Is there any way to manually allocate an object to the stack, not the heap?
2.5) If there is, would it be any faster to do that (for objects that don't escape the method), instead of having escape analysis have to figure it out? Or is there any way to tell Java something like "In this method, I need every object to be on the heap, don't bother trying to see if any can be on the stack"?

Thanks!

Björn Lindqvist
  • 19,221
  • 20
  • 87
  • 122
Sherz
  • 568
  • 2
  • 14

1 Answers1

1
  1. Yes. If appropriate. Are you familiar with Recursion? If not, see 1.
  2. new String("Foo")

2.5... What? Why are you trying to optimize the compile phase like that? What is the point?

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 1. In recursion, once the method ends, how is the returned object passed to the earlier method call, if it is allocated to the stack? 2. I thought that creates a reference to the String, which is stored on the heap. 2.5 For optimization, but really more out of curiosity. – Sherz Dec 03 '13 at 04:06
  • Make the first argument to your recursive function a reference to a List of Strings, recursively add Strings to your List... at the end of the recursion the stack allocated Strings are still referenced. – Elliott Frisch Dec 03 '13 at 04:08
  • That makes sense. And for 2 and 2.5? – Sherz Dec 03 '13 at 04:11
  • 2. I cheated a bit. String(s) go to an intern cache in Java... it's called PermGen space. 2.5 - There is no syntax for that, and the compiler works well... what are you trying to achieve? – Elliott Frisch Dec 03 '13 at 04:14
  • Like you said, to optimize it. Not that I think it really needs more optimization, but theoretically, I'd think it would work faster if it didn't have to do escape analysis. – Sherz Dec 03 '13 at 04:36
  • From a cost-benefit perspective the compile phase can be viewed as a [sunk cost](http://youarenotsosmart.com/2011/03/25/the-sunk-cost-fallacy/); further, if the compile phase needs [optimization](http://stackoverflow.com/questions/2094836/distributed-java-compiler) why not use a build farm? – Elliott Frisch Dec 03 '13 at 04:40