Re: Handling the throwable "ThreadDeath"
markspace wrote:
Eric Sosman wrote:
so the synchronization penalty is something
like 7.4 ns per operation.
This is a much smaller performance penalty that I was expecting. Given
that fact, I wouldn't hire the gang of interns either.
If you'd like to try it on your own machines, here's the code
I threw together:
public class StringSpeed {
public static void main(String[] unused) {
Object nop = new Object();
StringBuffer buf = new StringBuffer();
StringBuilder bld = new StringBuilder();
System.out.printf("%10s %10s %10s %10s\n",
"Count", "No-op", "Buffer", "Builder");
for (long reps = 1000000; reps > 0; ) {
long t0 = System.nanoTime();
for (long r = reps; --r >= 0; )
operate(nop);
long t1 = System.nanoTime();
for (long r = reps; --r >= 0; )
operate(buf);
long t2 = System.nanoTime();
for (long r = reps; --r >= 0; )
operate(bld);
long t3 = System.nanoTime();
System.out.printf("%10d %10d %10d %10d\n",
reps, t1-t0, t2-t1, t3-t2);
double dt = (t3 - t0) * 1E-9;
if (dt < 0.1)
reps *= 10;
else if (dt < 10.0)
reps *= 10.5 / dt;
else
break;
}
}
private static void operate(Object buff) {
}
private static void operate(StringBuffer buff) {
buff.append("abc");
buff.delete(0, 3);
}
private static void operate(StringBuilder buff) {
buff.append("abc");
buff.delete(0, 3);
}
}
I guess the lesson here is that optimization really does require careful
measurement, not just guessing at the performance of a routine by
eyeball. ;)
IMHO the real benefit of StringBuilder isn't that it's slightly
faster than StringBuffer at the places where you see it in the code,
but that it's faster where you *don't* see it. When StringBuilder
came along, javac started using it instead of StringBuffer in the
generated code for String concatenation. So just by recompiling the
existing source -- without changing a single character thereof --
you automatically switch from StringBuffer to StringBuilder and get
the accumulated benefit of all those small speedups.
--
Eric.Sosman@sun.com