There was an article in JDJ a couple of months ago that discussed the performance of StringBuffer's .append vs String concatenation. I am here to tell you, that our friend the Java Virtual Machine does some pretty weird optimizations. I would get vastly different results if I rearranged the order of the tests. Here are the four tests that I ran:
Each line above was surrounded by a for loop with a counter called i and looped through the above lines 1,000,000 times. Each test started out with a brand new StringBuffer that was created before the timer began.
The odd test of the bunch was buffy.append("<"+i+">");. Depending on its placement in the test, it would either be in second place or dead last. His time would get clobbered if he followed buffy.append("<").append(i).append(">"); who always had good times and is by far the best approach to use. Let the StringBuffer do your concatenation and conversion and you will have a winner everytime.
Posted by carl at March 4, 2004 06:03 PM
Comments