Garbage collection is very expensive.
In fact, for complex applications, garbage collection performance is competitive with manual malloc / free storage management. There is a classic article by Benjamin Zorn that clearly demonstrates this. In this article, Zorn describes how he modified some large large-load applications to use a conservative garbage collector instead of malloc and free . He then compared the original and modified versions of the applications. The result was comparable performance.
This document was published in "Practice and Experience in Using Software" in 1993. If you have not read it, you do not have the right to make statements about the "inefficiency" of garbage collection.
Please note that this study was conducted with a 1993 conservative garbage collector. Conservative collector - marking without any seal; that is, objects without garbage do not move. The latter means that allocating space for new objects is as slow and complicated as malloc . In contrast, modern garbage collectors (like Java 6/7) are collectible copy collectors that are much more efficient. And since copying compresses the remaining objects without garbage, distribution is much faster. This makes the GC even more competitive ... if you can find a way to make a comparison.
The developer does not have control over the GC, but he / she can manage or create the object. Then why not give them the opportunity to destroy objects?
It depends on what exactly you mean by "destruct".
In Java, you have the option to assign null . In some cases, this can accelerate the destruction of the object.
In Java, you can use finalizers and Reference types to notice that the object is about to be destroyed ... and something like that.
In Java, you can define a close() method (or equivalent) for any object and do something suitable. Then call it explicitly.
In Java 7, you have a “try with resources” construct to automatically call close() for resources when you exit the scope.
However, you cannot force a Java object to be deleted NOW. The reason this is not allowed is because it will allow the program to create dangling links, which can lead to heap failure and accidental JVM crashes.
This is NOT a Java way. The philosophy is that writing reliable programs is more important than efficiency. Although some aspects of Java do not follow this (e.g. streaming), no one wants the possibility of accidental JVM crashes.
Stephen c
source share