1. Prefer returning Empty Collections instead of Null
If a program is returning a collection which does not have any value, make sure an Empty collection is returned rather than Null elements. This saves a lot of “if else” testing on Null Elements.
2. Use Strings carefully
If two Strings are concatenated using “+” operator in a “for” loop, then it creates a new String Object, every time. This causes wastage of memory and increases performance time. Also, while instantiating a String Object, constructors should be avoided and instantiation should happen directly. For example:
3. Avoid unnecessary Objects
One of the most expensive operations (in terms of Memory Utilization) in Java is Object Creation. Thus it is recommended that Objects should only be created or initialized if necessary. Following code gives an example:
4. Dilemma between Array and ArrayList
Developers often find it difficult to decide if they should go for Array type data structure of ArrayList type. They both have their strengths and weaknesses. The choice really depends on the requirements.
- Arrays have fixed size but ArrayLists have variable sizes. Since the size of Array is fixed, the memory gets allocated at the time of declaration of Array type variable. Hence, Arrays are very fast. On the other hand, if we are not aware of the size of the data, then ArrayList is More data will lead to ArrayOutOfBoundException and less data will cause wastage of storage space.
- It is much easier to Add or Remove elements from ArrayList than Array
- Array can be multi-dimensional but ArrayList can be only one dimension.
5. When Finally does not get executed with Try
Consider following code snippet:
From the program, it looks like “println” inside finally block will be executed 5 times. But if the program is executed, the user will find that finally block is called only 4 times. In the fifth iteration, exit function is called and finally never gets called the fifth time. The reason is- System.exit halts execution of all the running threads including the current one. Even finally block does not get executed after try when exit is executed.
When System.exit is called, JVM performs two cleanup tasks before shut down:
First, it executes all the shutdown hooks which have been registered with Runtime.addShutdownHook. This is very useful because it releases the resources external to JVM.
Second is related to Finalizers. Either System.runFinalizersOnExit or Runtime.runFinalizersOnExit. The use of finalizers has been deprecated from a long time. Finalizers can run on live objects while they are being manipulated by other threads.This results in undesirable results or even in a deadlock.
No comments:
Post a Comment