-
Notifications
You must be signed in to change notification settings - Fork 0
String Concatenation
This example shows a more efficient way to concatenate large amounts of strings. You can try out this example in game with the command testPerformanceStrConcat
.
The intuitive way to do string concatenation in Java is to use the +
or +=
operators, as shown here:
String s = "";
for(int i=0; i<10000; i++) {
s += "Terasology";
}
However, this method is very inefficient. Since String
objects are immutable in Java, every concatenation has to instantiate a completely new one. Over 10,000 iterations, these start to add up and can cause noticeable slowdown. The solution is to use a mutable object to perform the concatenations, then use that to create a single immutable String
at the end. This is exactly what the StringBuilder
class is for. Using the StringBuilder.append
method, we can concatenate many strings without using lots of allocations, then use its toString
method to get a String
back, as shown here:
StringBuilder sb = new StringBuilder();
for(int i=0; i<10000; i++) {
sb.append("Terasology");
}
String s = sb.toString();
The performance benefits of the StringBuilder
approach are very easily apparent. Running the command in-game we can see that the first method takes several hundred milliseconds, causing a noticeable slowdown. The second method, however, executes so quickly it doesn't even take a whole millisecond, printing out a value of 0. Just from the command's built in timer it is clear that the StringBuilder
method is superior. However, we can see these results in Java Mission Control as well:
In this recording, the first method ran at 10:58 and the second one ran at 10:59. It is very clear that using +
for concatenation uses far more CPU time than using StringBuilder
.