devxlogo

Avoid Copying Immutable Objects Excessively

Avoid Copying Immutable Objects Excessively

One of the most common mistakes that most less-experienced Java programmers make is the unnecessary copying of immutable objects. The problem is compounded by the fact that it is not very easy to detect through testing. Immutable objects cannot change, and hence there is no need to copy them. The most common of immutable objects is the String object. For example:

 String s = new String("New String");

Effectively means that:

 String temp = "New String";String s = new String(temp);

Thus, a temporary String object is created unnecessarily, memory is allocated to it, the constructor is called, thus making the process an inefficient one. A better way would be to simply write:

 String s = "New String";

If you must change the contents of the String at all, you must instead use StringBuffer.

devx-admin

Share the Post: