Tuesday, February 01, 2005

String vs StringBuffer

On a lark, while a particularly long data load was going on, I wrote some code to try out timing the differences between doing string concatenation with a StringBuffer, versus just writing out String math. The different in timing was surprising.

Of course, no entry like this would be complete without quoting Hoare and Knuth, that Premature optimization is the root of all evil. If String math is clearer, it should be used until there is a clear reason to do otherwise, IMNSHO. There, I said it.

Having said it, I wrote this:


String bigLongString = "cranky ";
bigLongString += "poodle ";
for ( int i = 0; i < 100; ++i )
bigLongString += "frank ";
bigLongString += 25;
bigLongString += " times. Hoorah!";
return bigLongString;


and ran it 10,000 times. On my machine, it took around 14.2 seconds to run. I changed it thusly:


StringBuffer sb = new StringBuffer();
sb.append( "cranky " );
sb.append( "poodle " );
for ( int i = 0; i < 100; ++i )
sb.append( "frank " );
sb.append( 25 );
sb.append( " times. Hoorah!" );
return sb.toString();


and it took around 0.92 seconds to run 10,000 times. I changed it again to reuse the same StringBuffer (via sb.delete( 0, sb.length() );), and it took around 0.5 seconds to run 10,000 times.

That's a pretty stark difference in times, and pretty surprising, too, that reusing the StringBuffer would halve the execution time again as well.

(For the curious, "Cranky Poodle" is a parody of "Yankee Doodle", as can be found in the book Take Me Out of the Bathtub, by Alan Katz, and is a hilarious book.)

1 Comments:

Blogger javin paul said...

fantastic post , in my opinion The main benefit of String is immutablity which differentiate it from Stringbuffer but in case of string manipulation this advantage becomes biggest disadvantage and creates lots of garbage also using "+" operator for String concatanation is very slow as compared to StringBuffer.append()method which cost you some performance.

source: Difference among String vs StringBuffer vs StringBuilder

10:02 AM  

Post a Comment

<< Home