Creating objects consume time and resources, so optimization is required to make sure the performance of system is not impacted due to lot of unnecessary or temporary object creation. Similarly the correct usage of objects is equally important factor as it make a lot of difference as well. The following tips can help streamline your code for object creation and usage.

Creations Tips

  • Create only the required objects. Avoid creating intermediate objects.
  • Pre-Size collections (like Vector) to the expected size is more efficient than using the default size and letting the collection grow.
  • Create copies of simple arrays by initializing them, for complex arrays use cloning instead.
  • Defer initialization of objects or variables if they may never be used, saving resources and memory.
  • Clone arrays if that makes creation of array faster.
  • Simplify object structure by flattening it to reduce the number of nested objects it contains.
  • Keep the constructors simple and keep the inheritance hierarchies shallow.
  • Avoid creating an object that would be only used for accessing a method of that class.
  • Use the clone() method to create object as it by passes calling any constructors.

Usage Tips

  • Use int constants instead of String and other objects as constants. Compare these constants by identity(integers).
  • Use StringBuffer instead of concatenation operator(+) to concatenate Strings.
  • Use primitive data types like int instead of Objects like Integer for instance variables.
  • Reuse object where ever possible to avoid allocation and de-allocation.
  • Avoid wrapping primitive data types into classes (holders), use specific built in classes to handle primitive data types.
  • Avoid initializing the instance variables more than once.
  • Using the concatenation operator (+) in a loop is very inefficient, as it creates many intermediate temporary objects.
  • Avoid making copies of the object, rather then work on the object itself.
  • Cache frequently used objects whenever possible.

Pooling Considerations

  • Pooling is not always faster than object creation.
  • The efficiency of pooling objects compared to creating and disposing of objects is highly dependent on the size and complexity of the objects.
  • Object pools have deterministic access and reclamation costs for both CPU and memory, whereas object creation and garbage collection can be less deterministic

Avoid Object Creation Bottlenecks

  • Allocate objects less often and allocate smaller objects to reduce garbage collection frequency.
  • Eliminate object-creation bottlenecks by moving object creation to an alternative time.
  • Create objects early, when there is spare time in the application, and hold those objects until required.