Local database reading edition
Avoid Copying Immutable Objects
Reconstructed from database records, not a captured original forum layout. Dates and display names are retained as recorded; timezone and real-world identity are not inferred. Historical advice, contact details and offers are not current. Original markup is shown as inert text.
Forum index · Java - Tips Of The Day
Opening post
Asha · 2001-04-04 18:09:55
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:
<pre id=code><font face=courier size=2 id=code>
String s = new String("New String");
</font id=code></pre id=code>
Effectively means that:
<pre id=code><font face=courier size=2 id=code>
String temp = "New String";
String s = new String(temp);
</font id=code></pre id=code>
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:
<pre id=code><font face=courier size=2 id=code>
String s = "New String";
</font id=code></pre id=code>
If you must change the contents of the String at all, you must instead use StringBuffer.
Asha Balasubramanyan
http://www.ammu.org
Source notes
MyCommunity/nandighosha.org.zip!/forum/tools/snitz_forums_2000.mdb
Table: FORUM_TOPICS + FORUM_REPLY · record IDs: 76