To add some hard numbers, I wrote a simple test application:
public static void main(String[] args) {
int iterations = 1000000;
int secondIterations = 25;
long start = System.currentTimeMillis();
for (int count = 0; count < iterations; count++) {
StringBuilder builder = new StringBuilder();
for (int secondCounter = 0; secondCounter < secondIterations; secondCounter++) {
builder.append("aaassssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss");
}
}
System.out.println("Recreation took: " + Long.toString(System.currentTimeMillis() - start) + "ms");
start = System.currentTimeMillis();
StringBuilder builder = new StringBuilder();
for (int count = 0; count < iterations; count++) {
builder.delete(0, builder.length());
for (int secondCounter = 0; secondCounter < secondIterations; secondCounter++) {
builder.append("aaassssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss");
}
}
System.out.println("Reuse took: " + Long.toString(System.currentTimeMillis() - start) + "ms");
}
This gives the following output:
Recreation took: 10594ms
Reuse took: 1937ms
So, yes, as it seems reusing is indeed faster, at least if you test it in a tight loop with a small memory footprint. But please keep in mind that those numbers were generated by using 1 million iterations.
Keep two rules in mind:
- First go for readability and maintainability.
- Second...run a profiler.
This difference I see here is nothing I'd worry about until I really run into performance problems.