为什么Java编译器不是更聪明。假设是这样,那么它可以在编译时找出无法访问的对象,并通过代码本身清除垃圾。我认为这将有助于避免Java中的垃圾回收概念(需要添加DELETE关键字来删除对象)。为什么不可能呢?
通常,不可能在编译时知道程序中的什么时候确切地没有对象被引用(以便编译器可以在该点插入“删除”语句)。
Since Java 6 update 14, Java has escape analysis (as an experimental feature; it might become a standard feature in later versions) that partly solves this problem.
What happens with escape analysis is that the compiler checks if objects "escape" from some local scope; for example, local variables inside a method. If the compiler discovers that an object doesn't escape, Java will allocate the object on the stack instead of on the heap, which means that it will be discarded "for free" when the method returns (at that moment, the stack frame of the method ends and the object is discarded) - so the garbage collector doesn't have to do anything to clean up the object.