简体   繁体   中英

Java Method Invocation Stack Copy

In my understanding ( and according to https://www.javaworld.com/article/2076949/learn-java/how-the-java-virtual-machine-handles-method-invocation-and-return.html?page=2 ), the JVM handles Method Invocation as follows: Create new stack frame for callee Pop arguments from caller, push them to callee Execute callee.

But why do we have to copy/move the arguments from one stackframe to the other?

Wouldn't it be easier to create a new, overlapping stackframe for the callee, so that the topmost slots of the caller (containing the arguments) are now the bottommost slots for the callees stackframe. As long as we clean everything up afterwards (by popping) it should not make a difference but increase the efficiency of method calls by avoiding copying.

So what is the problem of this, why don't we do it this way?

The part you have cited, describes a formal process. The implementation must be compatible with that description, but doesn't have to be literally like that.

If you just read a few sentences beyond, you would have found:

The JVM specification does not require a particular implementation for the Java stack. Frames could be allocated individually from a heap, or they could be taken from contiguous memory, or both.

which explains why not every implementation could optimize it like you suggested, but

If two frames are contiguous, however, the virtual machine can just overlap them such that the top of the operand stack of one frame forms the bottom of the local variables of the next. In this scheme, the virtual machine need not copy objectref and args from one frame to another, because the two frames overlap. The operand stack word containing objectref in the calling method's frame would be the same memory location as local variable 0 of the new frame.

So nobody said, that it wouldn't be implemented the way you suggested, in fact, this optimization opportunity has been explicitly mentioned. But the article does not discuss which concrete JVM does implement the stack in which way.

It's also worth to keep in mind that for optimized hot spots, the invocation protocol might be entirely different, if not the callee got inlined into the caller, which would remove all invocation artifacts completely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM