Removing unnecessary calls to Java constructors
Original Publication Date: 2002-Jan-01
Included in the Prior Art Database: 2003-Jun-20
A program is disclosed to improve the performance of the java.lang.Class.newInstance() method. This Java* method creates a new object of the given class. It is usually implemented using a native method because an object must be created of an arbitrary type, which is not expressible in standard Java code. This native method must allocate space for the new object from the Java heap, then run the Java constructor for the class to complete the initialization of the object. To run the constructor the native code must call back into the Java Virtual Machine (JVM) to execute the constructor code. This can be complicated and can involve creating a new Java interpreter stack frame, calling the interpreter to execute the constructor, which could then result in a transition back to just-in-time compiled code for the constructor, before returning through the interpreter and the newInstance native method back to the caller. This invention optimizes this process for the common case of constructors which do nothing. The constructor for java.lang.Object does nothing it just returns. Therefore, there is no need to actually call it. Constructors for any other class will first call the object's superclass constructor. If the superclass constructor does nothing and the constructor itself does nothing then the constructor has no effect, therefore, need not be called. Calls to the superclass constructor have no effect if the superclass constructor is a null constructor. Constructors which just initialize fields to the default value for that field (0, 0.0, false or null) have no effect. A record is kept in the method block for the constructor of whether the constructor does anything useful. If the constructor is already noted as being a null constructor then there is no need to call it. If the constructor is already marked as being a non-null constructor then it must be called. If the constructor is marked as not yet examined then it needs to be examined. The byte codes of the constructor are examined to see if it does anything useful. If the constructor is just a return byte code then it is a null constructor. If the constructor calls a superclass constructor then the superclass constructor must be examined to see if it is a null constructor. Also the rest of the constructor must be examined to see if it has any effect. A constructor which just initializes fields to their default value has no effect.