Java: String concatenation, the right way, memory optimization.

Recently, I was published a plugin for Grails, when I did this, Grails developer made a small change in my String concatenations, and I want to share this:

Normally, we’re used to do String concatenations as:

String myString = "Hello";
myString += " Ignacio";
myString += " Ocampo";

In Oracle docs: “Strings are constant; their values cannot be changed after they are created.

This means, that each time that we assign new value to myString, we are creating new object. So, in the past example, we created 3 String objects.

When you are working with big apps, this causes memory heap size increase.

The right way to do it is using StringBuilder (A mutable sequence of characters) or StringBuffer (A thread-safe, mutable sequence of characters):

StringBuilder myStringBuilder = new StringBuilder();
myStringBuilder.append(" Ignacio");
myStringBuilder.append(" Ocampo");

To decide when to use one or the other, depends if you are working with threads or not. In the basic way, if your are working with a single-thread app, you could use StringBuilder.

One thought on “Java: String concatenation, the right way, memory optimization.

Leave a Reply

Your email address will not be published. Required fields are marked *