In this blog post, I’ll talk about String and StringBuilder.
String is immutable. Immutable means its contents cannot be altered.
String message = "I Love You"; message = "I Love You Beverly";
Consider the code above, the value of the message variable has not altered but actually java creates two different objects.
“I Love You” value does not garbage collected right away after being deferenced. The value is actually stored in “String Pool”, a special memory for Strings.
This is what happens in the String Pool after the code above is executed,
After the “I Love You” value is being deferenced, the value still exists in the String Pool. So that if the value is needed elsewhere in the application, java does not need to instantiate new String object.
Assuming the “I Love You” value is needed somewhere in the application, java does not instantiate new String object, it rather finds the existing value in the String Pool.
This helps with performance if certain strings are used over and over in the application because there are no cost of repeated String instantiation. However things get complicated if we try to “modify” a string.
String greeting = "Happy" greeting = greeting + " "; greeting = greeting + "Birthday"; greeting = greeting + " "; greeting = greeting + "Beverly";
As what I’ve discussed earlier, Strings are immutable, you can never modify a String, instead you create new one.
For the code above 9 String objects are instantiated:
- ” “
- “Happy “
- “Birthday “
- “Happy Birthday”
- “Happy Birthday “
- “Happy Birthday Beverly”
This is what happen in the String Pool
This could lead to large memory consumption because of multiple String instantiation. In the other words, performance will suffer if you will use String that will handle multiple string manipulations.
If your application needs to handle a lot of String manipulation, consider using StringBuilder.
StringBuilder is mutable sequence of characters unlike String.
Since StringBuilder is mutable, the contents of the strings can be altered without making multiple instantiation, hence, performance will not suffer.
Use String if have only few String manipulation like concatenating short messages.
If a string-manipulation might leave a lot of objects in the StringPool, or performance is a high priority, consider StringBuilder.