Friday, December 16, 2011

Java's character and assorted string classes support text-processing - 16


The StringBuffer class
String is not always the best choice for representing strings in a program. The reason: Its immutability causes String methods, such as substring(int beginIndex, int endIndex), to create new String objects, rather than modify the original String objects. In many situations, that leads to unreferenced Strings that become eligible for garbage collection. When many unreferenced Strings are created within a long loop, overall heap memory reduces, and the garbage collector might need to perform many collections, which can affect a program's performance, as the following code demonstrates:

String s = "abc";
String t = "def";
String u = "";
for (int i = 0; i < 100000; i++)
     u = u.concat (s).concat (t);

No comments: