[PJUG Javamail] StringBuilder vs +
Bullard, Douglas
Douglas.Bullard at nike.com
Thu Jun 18 14:19:16 EDT 2009
Good presentation by Chris Cowell-Shah the other night.
I'd mentioned that I'd seen that building simple strings with the "+"
sign was faster then using StringBuilder, and a lot of people challenged
that, so I wrote a little test to see if my memory was faulty.
I did three comparisons, warming up the VM so that any HotSpot
optimizations had taken place and the VM had stabilized. I used "+",
StringBuffer, and StringBuilder, for JDK 1.6, 1.5, and 1.4, running on
Windows.
Here are the results:
Test
JDK 1.6
JDK 1.5
JDK 1.4
StringBuffer
734
828
1375
StringBuilder
734
828
----
+
687
766
969
This confirmed my results, although the other guys were right - the
compiler does use StringBuilder internally.
Here is the guts of the test for StringBuilder - I create the string,
then add it to a list so it has to hand around:
for (int i = 0; i < numberOfLoops; i++){
StringBuilder sb=new StringBuilder();
sb.append("This").append("is").append("a").append("test").append("string
").append(i);
list.add(sb.toString());
The concatenation approach is the same:
for (int i = 0; i < numberOfLoops; i++){
String temp = "This " + "is " + "a " + "test " + "string" + i;
list.add(temp);
So, why the difference? Looking at the bytecode, it's obvious. The
compiler optimizes the concatenation of the "+" strings into a single
string at compile time - "This is a test string", then calls
StringBuilder to append the value of i.
Using a pure StringBuilder approach, it has to make multiple calls to
the append method at runtime.
The difference in performance is much less with JDK 1.6, but it's nice
to see that visually cleaner code is also more performant. We see this
a lot when people build up log messages, etc, and feel obligated to use
StringBuilder to make it "fast", and the result is a whole bunch of ugly
code. I like letting the compiler do the heavy lifting.
Douglas Bullard
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.pjug.org/pipermail/javamail/attachments/20090618/844089e8/attachment.html
More information about the Javamail
mailing list