Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll discuss whether to reuse a StringBuilder for efficiency. We’ll guide you on how to reuse the StringBuilder and explain its benefits.

2. Benefits

Reusing StringBuilder instances can help optimize an application’s memory usage and speed.

2.1. Optimize Object Creation

Instantiating new objects can be expensive in terms of memory and CPU usage. Since strings are immutable in Java, using a StringBuilder to concatenate different strings usually avoids unnecessary object creation. Reusing the string builder itself can also avoid additional overhead regarding memory allocation and garbage collection.

2.2. Improve Performance

StringBuilder objects are mutable, allowing us to change the object multiple times without creating a new object. This is significantly more performant than string manipulations.

2.3. Reducing Memory Usage

String objects are immutable, which means they cannot be modified after creation. When a String is modified, it creates a new object, which increases memory usage. By using StringBuilder instances, developers can avoid unnecessary object creation and reduce the amount of memory the application uses.

2.4. Improving Cache Reliability

When an application creates a new object, it will likely be allocated in a different memory location each time, leading to cache misses and reduced performance. By reusing StringBuilder instances, the same object can be used repeatedly, leading to better cache utilization and improved performance.

3. Example

In our first example, we’ll create a new StringBuilder object in every loop iteration:

for (int i = 0; i < 100; i++) {
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("baeldung");
    stringBuilder.toString();
}

Another way is to reuse the same StringBuilder object over and over again. In order to do this, we need to call the delete()-method at the end of each iteration in the StringBuilder and delete the whole char array that the StringBuilder contains:

StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 100; i++) {
    stringBuilder.append("baeldung");
    stringBuilder.toString();
    stringBuilder.delete(0, stringBuilder.length());
}

Instead of deleting the underlying char array, we can also set the length of the StringBuilder to zero after each iteration:

StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 100; i++) {
    stringBuilder.append("baeldung");
    stringBuilder.toString();
    stringBuilder.setLength(0);
}

Let’s compare the differences between the respective examples in a short benchmark

Benchmark                                                   Mode  Cnt    Score    Error  Units
Example 1: new StringBuilder object                           ss   10  210,661 ± 15,237  ms/op
Example 2: reuse StringBuilder with delete()                  ss   10  185,908 ±  7,802  ms/op
Example 3: reuse StringBuilder with setLength()               ss   10  164,323 ±  1,909  ms/op

We see that, as expected, object creation is the slowest in each iteration. Also, we can see that our example using setLength(0) is faster than delete(0, stringBuilder.length()). This is mainly because with setLength(), we only change the value of the count field of StringBuilder. This operation is fast. Whereas with the delete()-method, the StringBuilder object must delete the passed range of the characters.

In our case, the entire char array gets deleted by passing zero and the maximum length. Shifting characters in the array makes this operation much more complex. Therefore, using the setLength()-method is usually faster to achieve the same result.

4. When To Reuse StringBuilder

It is important to note that not all string manipulation operations require a StringBuilder. We can perform simple operations such as concatenating two strings without a StringBuilder. Also, we don’t need a reusable StringBuilder for all operations. We should use reusable StringBuilders for complex string manipulations that involve a large number of operations or iterations.

We also need to guarantee thread safety in concurrent applications. Without proper synchronization, multiple threads could use the same StringBuilder object, leading to unexpected behavior. Developers can ensure thread safety by using synchronized methods or locks to prevent race conditions. Alternatively, a class or thread can reuse the StringBuilder object only locally.

Sometimes it can also make sense to forego the reuse of the StringBuilder and the performance gained by it if it is not so important and instead make sure that the code is easily understandable and readable.

5. Conclusion

In this article, we discussed the advantages of reusing a StringBuilder and showed a concrete example of how to do it. Overall, reusing a StringBuilder can help reduce overhead and improve performance.

As always, the example code is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!