java performance![]()
by Glen McCluskey
Glen McCluskey is a consultant with 15 years of experience and
has focused on programming languages since 1988. He specializes in Java
and C++ performance, testing, and technical documentation
areas.
Consider first a couple of C examples, ones that output lines of the form: The maximum weight is 100 lbs. The first example simply prints this string repetitively:
include <stdio.h>
The second uses printf() to format the weight and units values:
#include <stdio.h>
The second program runs around 25 percent slower than the first because of the formatting overhead. Formatting is clearly a useful feature, but it's worth knowing what the costs are. With Java, a similar issue arises. To determine how expensive formatting is, we can write a series of programs. The first prints a string over and over:
public class format1 {
The second uses the string concatenation operator (+) to format values of variables:
public class format2 {
This code is slower than the first example because of the extra costs of converting integer values like "w" to strings, and because of costs in concatenating strings. The third example uses the Text.MessageFormat facility:
import java.text.*;
The idea here is that a format object of type MessageFormat is created
and then used. Placeholders like "{0}" in the format are
replaced with object values passed to the The final example is similar to the previous one, but it creates a message format on the fly:
import java.text.*;
In the previous example the message format was created once and then applied repetitively, allowing for some optimizations to be done. In this example, the format is passed in as a raw string each time. This approach is simpler but slower. The programs produce identical output. The running times are:
If you're trying to tune I/O performance in a Java application, the area of data formatting may be worth looking at.
|
![]() First posted: 14 Apr. 1999 jr Last changed: 14 Apr. 1999 jr |
|