Garbage Collection is very expensive.
In fact, for complex applications, the performance of garbage collection is competitive with manual storage management based on malloc
/ free
. There is a classic paper by Benjamin Zorn that clearly demonstrates this. In this paper, Zorn describes how he modified some large heap intensive applications to use a conservative garbage collector instead of malloc
and free
. Then he benchmarked the original and modified versions of the applications. The result was comparable performance.
This paper was published in Software Practice and Experience in 1993. If you haven't read it, you are not qualified to make pronouncements on the "inefficiency" of garbage collection.
Note that this research was done with a 1993-vintage conservative garbage collector. A conservative collector is mark-sweep without any compaction; i.e. non-garbage objects don't move. The latter means that allocation of space for new objects is as slow and complicated as malloc
. By contrast, modern garbage collectors (e.g. Java 6/7 ones) are generational copying collectors which are much more efficient. And since copying compacts the remaining non-garbage objects, allocation is much faster. This makes GC even more competitive ... if one could find a way to do the comparison.
Developer does not have control over GC but he/she can control or create object. Then why not give them ability to destruct the objects?
It depends on what precisely you mean by "destruct".
In Java, you do have the ability to assign null
. In some circumstances this may hasten the destruction of an object.
In Java, you can use finalizers and Reference
types to notice that an object is about to be destroyed ... and so something about it.
In Java, you can define a close()
(or equivalent) method on any object and have it do something appropriate. Then call it explicitly.
In Java 7, you have the "try with resources" construct for automatically calling close()
on the resources on scope exit.
However, you can't cause a Java object to be deleted NOW. The reason this is not allowed is that it would allow a program to create dangling references, which could lead to corruption of the heap and random JVM crashes.
That is NOT the Java way. The philosophy is that writing reliable programs is more important than efficiency. While certain aspects of Java don't follow this (e.g. threading) nobody wants the possibility of random JVM crashes.