Saturday, October 4, 2014

Be-Aware of the Performance of the String Concatenation...

                 The string concatenation operator (+) is a convenient way to combine a few strings into one. It is fine for generating a single line of output or for constructing the string representation of a small, fixed-size object, but it does not scale. Using the string concatenation operator repeatedly to concatenate n strings requires time quadratic in n. It is an unfortunate consequence of the fact that strings are immutable. When two strings are concatenated, the contents of both are copied.

For example, consider the following method that constructs a string representation of a billing statement by repeatedly concatenating a line for each item:


// In-appropriate use of string concatenation - Hits Performance drastically!

public String statement() {
     String res = "";
     for (int i = 0; i < numOfItems(); i++)
      res += lineOfItem(i); // String concatenation
      return res;
}

                 This method performs very slow if the number of items is large. To achieve acceptable performance, use a StringBuilder in place of a String to store the statement under construction. (The StringBuilder class, added in release 1.5, is an unsynchronized replacement for StringBuffer, which is now obsolete.)

public String statement() {
      StringBuilder sb = new StringBuilder(numItems() * LINE_WIDTH);
      for (int i = 0; i < numOfItems(); i++)
       sb.append(lineOfItem(i));
      return sb.toString();
}

                The difference in performance is dramatic. If numOfItems returns 100 and lineOfItem returns a constant 80-character string, the second method is 85 times faster than the first on my machine. Because the first method is quadratic in the number of items and the second is linear, the performance difference is even more dramatic for larger numbers of items. Note that the second method pre-allocates a StringBuilder large enough to hold the result. Even if it is retuned to use a default-sized StringBuilder, it is still fifty times faster.

                The moral is simple: don’t use the string concatenation operator to combine more than a few strings unless performance is irrelevant. Use StringBuilder’s append method instead. Alternatively, use a character array, or process the strings one at a time instead of combining them.