Monday, July 21, 2008

Java benchmark: String, StringBuilder, and StringBuffer

Some results first comparing String, StringBuilder and StringBuffer, with and without pre-allocation.

100000 times
String: 30786
StringBuilder (no pre-alloc): 5
StringBuilder (pre-alloc): 3
StringBuffer (no pre-alloc): 6
StringBuffer (pre-alloc): 5

The results clearly show how bad String is if you need to change it constantly in comparison to StringBuilder or StringBuffer. Now, let's remove String and compare StringBuilder and StringBuffer further:

1000000 (one million) times
StringBuilder (no pre-alloc): 58
StringBuilder (pre-alloc): 42
StringBuffer (no pre-alloc): 142
StringBuffer (pre-alloc): 122

This benchmark seems to prove to me that StringBuilder, introduced in Java 1.5, is really the best option when running in a single thread. And one can see that the overhead of running StringBuffer, which is synchronized, is actually huge.

Excerpt of my code to run this benchmark (*):
  final int n = 100000;
final String a = "a";

String s = "";
Date start = new Date();
for (int i = 0; i < n; ++i)
{
s = s + a;
}
Date end = new Date();
System.out.println("String: " +
(end.getTime()-start.getTime()));

StringBuilder sb = new StringBuilder();
start = new Date();
for (int i = 0; i < n; ++i)
{
sb.append(a);
}
end = new Date();
System.out.println("StringBuilder (no pre-alloc): " +
(end.getTime()-start.getTime()));


(*) Based on this post, which does not compare StringBuffer
Post a Comment