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.

  1. This was really helpful, thanks for the post !

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *

Puedes usar las siguientes etiquetas y atributos HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation