There are techniques for creation of objects (read allocation of memory)
widely known as lazy Instantiation and Eager Instantiation.
Lazy instantiation is a memory conservation technique, by which, a program
delays the creation of objects until those objects are needed.
In Java, there are two categories of lazy instantiation:
1. Lazy class loading
The Java runtime loads classes into memory only when they're first
referenced.
This may happen due to a first call to a static method of a class as in:
aClass.someStaticMethod();
or a first call to the "new" operator to create an instatnce of a class as
in:
AClass aClass = new AClass();
This is a very important feature of the Java runtime. Memory usage can be
significantly reduced. For example, if a part of a program is never run,
classes that are only referenced by that part of the program will never be
loaded.
2. Lazy object creation
This is tightly coupled to lazy class loading. It refers to when you delay
the creation of an instance of a class until you really need it in the code.
Eager Instantiation, on the other hand, refers to technique that instances
of objects are created before any part of the code actually asks for them.
This may considerably improve runtime performance since live objects are
sitting in runtime memory waiting to be called. An example of eager
instantiation is creation of resource pools, e.g. a pool of database
connections waiting for client calls.
Suppose you have to load images on request based
corresponding image file names. You can write code like:
public class AnImageFile
{
private String m_filename;
private Image m_image;
public AnImageFile(String filename)
{
m_filename=filename;
//Now load the image in constructor
}
public String getName(){ m_return filename;}
public Image getImage(){return m_image;}
}
This is an eager approach that guarantees the availability of an image right
after creation of an instance of AnImageFile class. This will boost
performance when a call to getImage(...) is made. But if you have many
images, and create AnImageFile instances of them, you may use up a lot of
memory unnecessarily. You can trade performance benefits to memory uasage
via lazy instantiation, as in:
public class ImageFile
{
private String m_filename;
private Image m_image=null;
public ImageFile(String filename)
{
//Here we just store the filename
m_filename=filename;
}
public String getName(){ return m_filename;}
public Image getImage()
{
if(m_image==null)
{
//load the image
}
return m_image;
}
}
Here, the actual image is loaded only on the first call to getImage().
So, you can reduce memory usage and startup time by using lazy instantiation
and paying the price for performance hit when you create an object when it
is actually need. Or, you can increase the startup time, and use up more
memory upfront to eagerly instantiate objects in order to boost performance.