View RSS Feed

Advanced Java

Unnecessary Object Creation with Immutable Objects

Rate this Entry
by , 11-29-2011 at 11:05 PM (2276 Views)
Programmers are often not aware of how to create objects that can be reused. The key to understanding how to create reusable objects is that they must be immutable. 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.

Rather than create a new String instance.

Java Code:
public void BuildingLoop{
	int total = 10;
	
	for(int i=0; i< total; i++){
		String str = new String("XXXYYYZZZ-AAABBBCCC" + String.valueOf(i));
		.....
	}
}

You need to reuse the existing instance.

public void BuildingLoop{
	int total = 10;
	
	for(int i=0; i< total; i++){
		String str = "XXXYYYZZZ-AAABBBCCC" + String.valueOf(i);
		.....
	}
}

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

Comments