Initialization
All
chained
constructors
are automatically called when creating an object with
new. Chaining more constructors for a particular
object causes extra
overhead at
object creation, as does initializing instance variables more than
once
.
Be aware of the default values that Java initializes variables to:
nullfor objects0for integer types of all lengths (byte,char,short,int,long)0.0for float types (floatanddouble)falseforbooleans
There is no need to reinitialize these values in the constructor (although an optimizing compiler should be able to eliminate the extra redundant statement). Generalizing this point: if you can identify that the creation of a particular object is a bottleneck, either because it takes too long or because a great many of those objects are being created, you should check the constructor hierarchy to eliminate any multiple initializations to instance variables.
You can avoid constructors by unmarshalling objects from a serialized
stream, because deserialization does not use constructors. However,
serializing and deserializing objects is a CPU-intensive procedure
and is unlikely to speed up your application. There is another way to
avoid constructors when creating objects, namely by creating a
clone( )
of an object. You can create new
instances of classes that implement the
Cloneable
interface using the clone() method. These new instances do not call any class constructor, thus allowing you to avoid the constructor initializations. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access