Posts

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