View RSS Feed

Advanced Java

Unnecessary Object Creation with Mutable Objects

Rate this Entry
by , 11-29-2011 at 10:59 PM (1032 Views)
Continuing with our last tip on immutable objects, we now look at re-using mutable objects. Although you cannot modify a mutable object, you can avoid unnecessarily waste memory by reusing the existing instance. So consider for example mutable Date objects. Once the values are computed, they are never modified. So for example if you a running a loop in which each loop a string instance is required, rather than create a new instance every time it executes, you simply reuse the existing instance.

Avoid allocating Calendar objects in this manner as it is very expensive.

Java Code:
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class SeniorBenefits {
	
	private static Date birthDate;
	private static final int BENEFITAGE = 65;
	
	public boolean isQualified(){
		Calendar gmtCal = 
				Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		Calendar birthCal = 
				Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		birthCal.set(1955, 6, 9);
		birthDate = birthCal.getTime();
		int thisYear = gmtCal.get(Calendar.YEAR);
		int benefitYear = thisYear - BENEFITAGE;
		gmtCal.set(benefitYear, Calendar.JANUARY, 1, 0, 0, 0); 
		Date benefitStart = gmtCal.getTime(); 
		return birthDate.compareTo(benefitStart) <= 0;
	}
	

}
The best way to approach this and avoid the inefficiency of expensive allocations when the method is call multiple for Calendar objects, is to use a static initializer.

Java Code:
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class SeniorBenefits {
	
	private static Date birthDate;
	private static Date benefitStart;
	private static final int BENEFITAGE = 65;
	
	static{
		// Create objects in this manner 
		Calendar gmtCal = 
				Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		Calendar birthCal = 
				Calendar.getInstance(TimeZone.getTimeZone("GMT"));
		birthCal.set(1955, 6, 9);
		birthDate = birthCal.getTime();
		int thisYear = gmtCal.get(Calendar.YEAR);
		int benefitYear = thisYear - BENEFITAGE;
		gmtCal.set(benefitYear, Calendar.JANUARY, 1, 0, 0, 0); 
		benefitStart = gmtCal.getTime(); 
	}
		
	public boolean isQualified(){
		return birthDate.compareTo(benefitStart) <= 0;
	}
	

}

Submit "Unnecessary Object Creation  with Mutable Objects" to Facebook Submit "Unnecessary Object Creation  with Mutable Objects" to Digg Submit "Unnecessary Object Creation  with Mutable Objects" to del.icio.us Submit "Unnecessary Object Creation  with Mutable Objects" to StumbleUpon Submit "Unnecessary Object Creation  with Mutable Objects" to Google

Comments