Wednesday, October 8, 2008

Java performance: Strings

Here's a short report about different Strings concatenation methods I performed.

Strings joining is very often repeated operation.

String str1 = "Mary had ";
String str2 = "a little ";

String finalStr = str1 + str2 + " lamb";

Did you know that creating finalStr will cost you 3 String object creations? Maybe it's somehow optimized inside JVM but still takes very long time and resources. The solution is to use StringBuffer (synchronized) or StringBuilder (not synchronized). Difference between StringBuffer and StringBuilder is that StringBuffer is thread-safe which means that finalString could be assembled by few concurrent threads. But if you don't need multithreaded string concatenating (which is the most often case!) use StringBuilder.

Below is the time comparison of three concatenation methods. First I joined 10 strings (often case) and then I checked work time for 1000 strings which will point out sharply performace differences. (Time is given in microseconds)

10 strings

+ concatenation: 126us
StringBuffer: 23us
StringBuilder: 11us

1000 strings

+ concatenation: 11810us (11.81ms)
StringBuffer: 253us
StringBuilder: 123us

Use StringBuilder!

No comments:

Post a Comment