Java Reference
In-Depth Information
Timing results
I ran StringPrintA , StringPrintAA , and StringPrintB twice each on the same computer.
To eliminate JVM startup times, I ran them from a program called TimeNoArgs , which takes
a class name and invokes its main() method, using the Reflection API. TimeNoArgs and a
shell script to run it, stringprinttimer.sh , are in the performance folder of the javasrc source
repository. Here are the results:
2004 Results
StringPrintA
17.23, 17.20 seconds
StringPrintAA 17.23, 17.23 seconds
StringPrintB
27.59, 27.60 seconds
2014 Results
StringPrintA
0.714, 0.525 seconds
StringPrintAA 0.616, 0.561 seconds
StringPrintB
1.091, 1.039 seconds
Although the times went down by a factor of roughly 20 over a decade, the ratios remain re-
markably consistent: StringPrintB , which calls print() and println() multiple times,
takes roughly twice as long.
Moral: Don't guess. If it matters, time it.
Another moral: Multiple calls to System.out.print() cost more than the same number of
calls to a StringBuilder 's append() method, by a factor of roughly 1.5 (or 150%). Theory
B wins; the extra println calls appear to save a string concatenation but make the program
take substantially longer.
Other aspects of performance: GC
There are many other aspects of software performance. One that is fundamental to Java is
garbage collection behavior. Sun/Oracle usually talk about this at JavaOne. See, for example,
the JavaOne 2003 paper “Garbage Collection in the Java HotSpot Virtual Machine” . You
should also see the JavaOne 2007 talk by the same GC Development team, “Garbage-
Collection-Friendly Programming”, TS-2906. Unfortunately it seems to have gotten lost
Search WWH ::




Custom Search