Most developers understand that early optimization of code almost always produces the wrong outcomes. In a recent interview with Sun Developer Network, Heinz Kabutz, a Java Champion and author of the Java Specialist newsletter, illustrates this point in the context of String concatenation:
In the early days of Java programming, I sometimes resorted to "clever" coding. For example, when I was optimizing a system ... I changed the String
addition to use StringBuffer
after we had optimized the architecture and design of the system and wanted to improve things a bit...
String
is immutable, so the compiled code will create many intermediate String
objects, which can strain the garbage collector... A common remedy is to introduce StringBuffer
...
StringBuffer result = new StringBuffer();
result.append(s1);
result.append(s2);
result.append(s3);
result.append(s4);
result.append(s5);
result.append(s6);
return result.toString();
Using JDK 6.0_02 and the server HotSpot compiler, I can execute [a version based on simple String concatenation] a million times in 2013 milliseconds, but [the StringBuffer-based version] in 734 milliseconds. At this point, I might congratulate myself for making the code three times faster. However, the user won't notice it if 0.1 percent of the program becomes three times faster...
Sun introduced the StringBuilder
class in J2SE 5.0, which is almost the same as StringBuffer
, except it's not thread-safe. Thread safety is usually not necessary with StringBuffer
, since it is seldom shared between threads. When Strings
are added using the + operator, the compiler in J2SE 5.0 and Java SE 6 will automatically use StringBuilder
. If StringBuffer
is hard-coded, this optimization will not occur.