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"; System.out.println(myString);
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.
StringBuilder myStringBuilder = new StringBuilder(); myStringBuilder.append("Hello"); myStringBuilder.append(" Ignacio"); myStringBuilder.append(" Ocampo"); System.out.println(myStringBuilder.toString());
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.