String vs StringBuilder: What Every Java Developer Should Know
If you want to write optimal Java code, it’s important to understand the differences between String and StringBuilder. Knowing these differences can help you optimize your software engineering practices.
In this blog post, we’ll take a quick look at the key differences between the two and run a script to test the performance benefits of StringBuilder, an important tool in your software engineering toolkit.In Java, a String
is an immutable object, which means once it is created, its contents cannot be changed. On the other hand, a StringBuilder
is a mutable object, which means you can modify its contents without creating a new object.
Here are some key differences between String
and StringBuilder
:
- Immutable vs. Mutable: As mentioned,
String
is immutable, whileStringBuilder
is mutable. - Performance: Because
String
is immutable, if you want to modify its contents, you need to create a new object. This can be slow and memory-intensive if you're working with large strings or performing many modifications. In contrast,StringBuilder
can modify its contents in-place, without creating new objects, making it faster and more memory-efficient for string manipulation. - Thread safety:
String
is thread-safe because it is immutable, which means it can be shared between multiple threads without the risk of data corruption. In contrast,StringBuilder
is not thread-safe because it is mutable. If multiple threads modify the sameStringBuilder
instance concurrently, it can lead to data corruption. - Usage:
String
is typically used to represent a fixed sequence of characters, whileStringBuilder
is used for dynamic string manipulation. If you have a string that needs to be modified frequently,StringBuilder
would be the more appropriate choice.
In summary, if you need a string that won’t change, use String
. If you need to manipulate a string frequently, use StringBuilder
.
Let’s put what we’ve learned through a test
Here, we have a Java program that compares the performance of String
vs StringBuilder
when adding 1,000,000 words to a string using a loop:
public class StringVsStringBuilder {
public static void main(String[] args) {
int numOfWords = 1000000;
String str = "";
StringBuilder stringBuilder = new StringBuilder();
// Time adding to String
long start = System.currentTimeMillis();
for (int i = 0; i < numOfWords; i++) {
str += "word ";
}
long end = System.currentTimeMillis();
long timeTakenString = end - start;
System.out.println("Time taken to add " + numOfWords + " words to String: " + timeTakenString + "ms");
// Time adding to StringBuilder
start = System.currentTimeMillis();
for (int i = 0; i < numOfWords; i++) {
stringBuilder.append("word ");
}
end = System.currentTimeMillis();
long timeTakenStringBuilder = end - start;
System.out.println("Time taken to add " + numOfWords + " words to StringBuilder: " + timeTakenStringBuilder + "ms");
}
}
This program first initializes an empty String
and an empty StringBuilder
. Then, it adds 1,000,000 words to each object using a loop. We use the System.currentTimeMillis()
to timestamp the difference in performance.
The results 🤯:
As you can see, the difference in String manipulation is like night and day. The StringBuilder
approach is significantly faster than the String
approach, especially for large numbers of additions like this one.
Let’s try the same process, but with 5,000 words. Same code, different result:
Weeell, milliseconds couldn’t give us any justice here.. 😅
I hope that you have a better understanding of the differences between String and StringBuilder now. This knowledge is crucial for optimizing your Java code, especially when working with a lot of string manipulation and concatenation. With this understanding, you’ll be able to explain to your colleagues why using StringBuilder is a smart choice for software engineering practices.