Java Reference
In-Depth Information
StringBuilder versus String 
try it out
Different classes can be used for working with strings. This exercise will help you differentiate two
common classes: String and StringBuilder .
1.
Create a StringTester class in Eclipse with the following content:
class StringTester {
public static void main(String[] args) {
String string = "";
long startTime1 = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
string += "a";
}
long endTime1 = System.currentTimeMillis();
StringBuilder stringBuilder = new StringBuilder();
long startTime2 = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
stringBuilder.append("b");
}
long endTime2 = System.currentTimeMillis();
System.out.println("String took: "+(endTime1-startTime1)+"ms");
System.out.println("StringBuilder took: "+(endTime2-startTime2)+"ms");
}
}
2.
Run this piece of code to benchmark the performance of String (100,000 times adding a charac-
ter) with StringBuilder .
How It Works
Now take a look at how it works.
1.
This code benchmarks the performance of the StringBuilder class against normal strings, by per-
forming 100,000 single character concatenations. The example uses a for loop here, which I've not
discussed in-depth yet, but the meaning is clear—you simply count from 0 to 100,000.
2.
When running the benchmark, you should get something like the following output. Observe the
drastic difference:
String took: 3231ms
StringBuilder took: 5ms
classes in the java.io and java.nio packages
The java.io package provides classes to deal with input and output, for instance to deal with read-
ing and writing files. In Java SE 1.4, New IO ( java.nio ) was added to optimize performance and to
include a number of new features. Chapter 7 discusses how to deal with files in detail, and you will
revisit these classes there.
 
Search WWH ::




Custom Search