Java Reference
In-Depth Information
hope) your web site to be sufficiently busy so that doing this efficiently will make a differen-
ce. There are two ways of thinking about this:
▪ Theory A: This string concatenation is inefficient.
▪ Theory B: String concatenation doesn't matter; println() is inefficient, too.
A proponent of Theory A might say that because println() just puts stuff into a buffer, it is
very fast and that string concatenation is the expensive part.
How to decide between Theory A and Theory B? Assume you are willing to write a simple
test program that tests both theories. Let's just write a simple program both ways and time it.
Example 23-8 is the timing program for Theory A.
Example 23-8. StringPrintA.java
public
public class
class StringPrintA
StringPrintA {
public
public static
void main ( String [] argv ) {
Object o = "Hello World" ;
for
static void
for ( int
int i = 0 ; i < 100000 ; i ++) {
System . out . println ( "<p><b>" + o . toString () + "</b></p>" );
}
}
}
StringPrintAA (in the javasrc repo but not printed here) is the same but explicitly uses a
StringBuilder for the string concatenation. Example 23-9 is the tester for Theory B.
Example 23-9. StringPrintB.java
public
public class
class StringPrintB
StringPrintB {
public
public static
void main ( String [] argv ) {
Object o = "Hello World" ;
for
static void
for ( int
int i = 0 ; i < 100000 ; i ++) {
System . out . print ( "<p><b>" );
System . out . print ( o . toString ());
System . out . print ( "</b></p>" );
System . out . println ();
}
}
}
Search WWH ::




Custom Search