Wednesday, August 5, 2009

Performance improvement techniques in Object creation

Reference: http://www.precisejava.com/javaperf/j2se/Objects.htm

Note: This section assumes that reader has some basic knowledge of Java.

Optimization techniques in Object creation

  • Avoid creating objects in a loop.
  • Always try to use String literals instead of String objects.

Eg . String str1 = "Hello I am here "; //String literal

String str2= "Hello I am here "; //String literal

String str3 = new ("Hello I am here "); //String Object

When we create a String without the new operator and if the content is already existing it uses a single instance of the literal instead of creating a new object every time.

  • Never create objects just for accessing a method.
  • Whenever you are done with an object make that reference null so that it is eligible for garbage collection.
  • Never keep inheriting chains long since it involves calling all the parent constructors all along the chain until the constructor for java.lang.Object is reached.
  • Use primitive data types rather than using wrapper classes.
  • Whenever possible avoid using class variables, use local variables since accessing local variables is faster than accessing class variables.
  • Use techniques such as lazy evaluation. Lazy evaluation refers to the technique of avoiding certain computations until they are absolutely necessary. This way we put off certain computations that may never need to be done at all.
  • Another technique is Lazy object creation : i.e. delaying the memory allocation to an object till it is not being put into use. This way a lot of memory is saved till the object is actually put in to use.

Key Points

  1. Avoid creating objects in a loop.
  2. Use String literals instead of String objects (created using the 'new' keyword) if the content is same.
  3. Make used objects eligible for garbage collection.
  4. Do not keep inheritance chains long.
  5. Accessing local variables is faster than accessing class variables
  6. Use lazy evaluation, lazy object creation whenever possible.

No comments: