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.

See also  5 Tips for Working With an Onsite Interpreter
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist