Tuesday, May 13, 2008

Java optimization and performance

No new Exception if not needed

Many of us do this when we want to throw an error. But if you are throwing exception from another catch, then don't make new exception object. Keep throwing the same exception which you caught if possible. This will be better for performance. And also in new exception usually we change the description only to reflect the perfect error cause, but other ways are there to track it.

Avoid excessive synchronization

Yah threading can be a bit complex situation sometimes in java. And we all use synchronization to avoid dead locks. But it needs a more attention then we give it. Try to make a block of code synchronized rather then making the whole method synched. The whole method will stop all other threads, waiting to go inside it. It will generate more overhead. So keep the design like we need less sync code.

Release DB and File IO

This is the most case in which we all do something wrong.
DB connections must be closed after completing your DB transactions because its a limited resource.

Also if you are using File IO, then must close file streams after completing the task.

Best way for this is, to write the releasing code in 'finally' block of the method.

Use StringBuffer/StringBuilder rather than String

We use string manipulations in our daily coding many times. And all we do is always making new String object. As most of us know, String is immutable object (which means once assigned you can't change its value), so when you assign existing String object another value, it will make new String object. And most string operation generates lot of small String objects.

If it’s possible to use StringBuffer or StringBuilder instead of String then its more more way better. Because it will be one object having all your data in it and you can get String form it when you want.

Now StringBuilder is nonSynchronized and StringBuffer is synchronized. So if you don't have threading issues and don't need Sync, then you must use StringBuilder which is included since jdk 1.5.

Later on we will talk about more points also when i remember them :)

0 Comments: