<quote>
Language performance (in general) is relative to what you compare it to.
The following scorecard was interesting to me.
http://dada.perl.it/shootout/craps.html
Object instantiation under Java is nearly identical to Borland C, and about
57 times faster than Ruby. But string concatenation under Borland C is 24
times faster than Java. Word count is 5.7 times faster under Borland C than
Java. A "Hello World" benchmark is 60 times faster under Borland C than
Java.
</quote>
You will likely see better results if you use a StringBuilder rather than a
StringBuffer.
public class TestClass {
public TestClass() {
}
/**
* @param args
*/
public static void main(String[] args) {
printStringBuffer(500000);
printStringBuilder(500000);
}
public static void printStringBuffer(int n) {
Date start = new Date();
String hello = "hello\n";
StringBuffer stringBuffer = new StringBuffer(32);
for (int i = 0; i < n; i++) {
stringBuffer.append(hello);
}
Date end = new Date();
System.out.printf("%-20s %tb %tb Diff: %d\n", "String Buffer: ",
start, end, (end.getTime() - start.getTime()));
}
public static void printStringBuilder(int n) {
Date start = new Date();
String hello = "hello\n";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(hello);
}
Date end = new Date();
System.out.printf("%-20s %tb %tb Diff: %d\n", "String Builder: ",
start, end, (end.getTime() - start.getTime()));
}
}
Results on Windows:
String Buffer: Mon Apr 27 16:54:30 PDT 2009 Mon Apr 27 16:54:30 PDT
2009 Diff: 94
String Builder: Mon Apr 27 16:54:30 PDT 2009 Mon Apr 27 16:54:30 PDT
2009 Diff: 47
--
James R. Perkins
As an Amazon Associate we earn from qualifying purchases.