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. #1 by emt training on August 21, 2010 - 9:57 pm

    Terrific work! This is the type of information that should be shared around the web. Shame on the search engines for not positioning this post higher!

(will not be published)

Please leave these two fields as-is:

Protected by Invisible Defender. Showed 403 to 1,915 bad guys.