With the Java VM, how are object references treated
During the execution of a Java application, are object references used by the runtime or are they stripped away at compile time?
I guess I could decompile class files and see h开发者_JAVA百科ow they are used as local variables and member variables.
Is it wasteful to create an object reference when you don't need to or will the compiler strip away unneeded references?
E.g.
final String abc = "abc"; method(abc);
as opposed to:
method("abc");
Methods are stored in the object data area (as laid out by the class definition), but block local references are stored in a special area of the JVM stack frame. When the frame pops off of the frame stack of the executing thread, all the block local references are lost as they are not actually stored in the object's data structures.
Note that if you are unfamiliar with JVM stack frames, a new stack frame is obtained for the entry into every method, and is popped off the Thread's stack when returning from a method. Stack frames contain a number of elements, including a pointer to the current instruction (which is located in the Class's instruction pages) a pointer to the "this" object, and a small stack to hold intermediates in the current method calculation. Sometimes a variable reference doesn't incur any need for storage, and many optimizing compilers will then compile out the code to use the local stack instead of the "object reference storage" meaning that reversing of the code will result in not discovering that the person used a variable at all.
The "this" pointer always occupies the first entry in the object reference storage area, and all of these concepts are conceptual. The actual implementation only needs to conform to the operational standard, it doesn't need to conform to a particular memory layout.
At the bytecode level, "unnecessary" references like this will not be stripped out; you could see the above assignment in the bytecode. But the JIT (i.e., HotSpot) is generally much smarter, and so the runtime impact is essentially zero.
In the particular case you mention, the fact that you name a local variable and call it "abc" is essentially a convenience for you as the programmer. Whether or not you do so or just leave it as an unnamed parameter, the bytecode will essentially end up the same.
In general, you don't need to worry about that level of detail. You can trust the bytecode compiler and JIT compiler to do sensible things. If you had to worry down to this level of detail, it would be practically impossible to write any application of moderate complexity...
[P.S. If you have the time and interest, I would also recommend that you do decompile the corresponding classes just as an educational exercise. But what you will find should be quite reassuring: that the compiler is doing generally sensible things and there's no need to be paranoid.]
精彩评论