Patricia said:
The actual performance is going to be very dependent on the operation
mix.
I have a StringBuffer test program that do a mix of append and
substring combined with some String operations.
StringBuffer results says 1.11 while StringBuilder
results say 1.18 on 32 bit Win32 SUN Java 1.5.
(code attached in StringBuilder incarnation below for the curious)
That is a 6% difference.
I am not surprised that the difference is not bigger.
The synchronized overhead has become smaller in newer
JVM's.
And the code do other things than just StringB*
operations. But so do real world applications.
Arne
===================================================
import java.text.NumberFormat;
import java.text.DecimalFormat;
import java.util.Random;
public class JvmTest {
private final static int REP = 10;
private final static int NSTR = 100;
private final static int N = 1000000;
private final static String ALFA = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static NumberFormat nf = new DecimalFormat("0.00");
private static Random rng = new Random();
private static int scale;
private static void printres(long t1, long t2, int n1, int n2,
String ops) {
double xperf = (double)n1 * (double)n2 / ((t2 - t1) / 1000.0) ;
String sperf= nf.format(xperf/1000000);
System.out.println(sperf + " million " + ops + " per second");
}
public static void teststr() {
int nstrscale = NSTR / scale;
long t1 = System.currentTimeMillis();
for(int i = 0; i < nstrscale; i++) {
StringBuilder sb = new StringBuilder("");
for(int j = 0; j < N; j = j + 10) {
String s = ALFA + ALFA;
int ix = (i + j) % ALFA.length();
sb.append(s.substring(ix, ix + 1) + s.substring(ix + 1,
ix + 3) + s.substring(ix + 3, ix + 6) + s.substring(ix + 6, ix + 10));
}
int ix = rng.nextInt(N);
if(sb.length() != N || sb.charAt(ix) != ALFA.charAt((i +
ix) % ALFA.length())) {
System.out.println("String test error");
System.exit(0);
}
}
long t2 = System.currentTimeMillis();
printres(t1, t2, nstrscale, N / 10, "string operations");
}
public static void main(String[] args) {
System.out.println(System.getProperty("java.vm.vendor") + " " +
System.getProperty("java.vm.name") + " " +
System.getProperty("java.vm.version"));
if(args.length > 0) {
scale = Integer.parseInt(args[0]);
} else {
scale = 1;
}
for(int i = 0; i < REP; i++) {
teststr();
}
}
}