Posts Tagged API

String concatenation

One of the first things developers learn about String concatenation in Java is that the “+” operation does the magic. In this case the magician is the compiler. Lets look how the following code snippet gets translated by the compiler.

// Sample.java
String buffer = "";
for (String string : listOfStrings)
{
  buffer += string;
}
// Sample.class
String buffer = "";
for (String string : listOfString)
{
  buffer = new StringBuilder(buffer).append(string).toString();
}

Every time the String concatenation is invoked a new StringBuilder instance is created and but never assigned. Hence it is immediately eligible for Garbace Collection. What a waste of Memory. If you really need to concat Strings in a loop you better do it directly with a StringBuilder.

,

1 Comment