Java Objects Best Practices
Object contain data and methods to manipulate the data. Whenever we create an object there is an overhead involved. When an object is created
- Memory is allocated to all the variables
- All super class variables are also allocated memory
- All sub class variables, super class variables are initialized .
- The constructor is invoked.
So whenever we create an object the above steps are repeated which take considerable resources so it is very important to decide whether creating a new object is required or not. All objects are placed on heap, their address on the heap is stored in the stack. All class variables are stored in the method area. All primitive data types are stored on the stack.
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
- Avoid creating objects in a loop.
- Use String literals instead of String objects (created using the 'new' keyword) if the content is same.
- Make used objects eligible for garbage collection.
- Do not keep inheritance chains long.
- Accessing local variables is faster than accessing class variables
- Use lazy evaluation, lazy object creation whenever possible.
Tags: java objects, best practices, data types, garbage collection, lazy object creation
Can't find what you're looking for? Try Google Search!
Comments on "Java Objects Best Practices"