![]() |
VOOZH | about |
StringBuilder is used to represent a mutable string of characters. Mutable means the string which can be changed. So String objects are immutable but StringBuilder is the mutable string type. It will not create a new modified instance of the current string object but performs modifications on the same StringBuilder object without creating a new object.
The complete functionality of StringBuilder is provided by StringBuilder class which is present in System.Text namespace.
| Feature | String | StringBuilder |
|---|---|---|
| Mutability | Immutable (cannot be changed after creation) | Mutable (can be changed without creating new objects) |
| Performance | Slower for frequent modifications | Faster for frequent modifications |
| Memory Usage | Creates a new object for each modification | Modifies the same object, reducing memory overhead |
| Use Case | Use for small or infrequently modified strings | Use for large or frequently modified strings |
| Modification Methods | Modification requires creating a new string | Modification is done in-place |
| Thread Safety | Strings are thread-safe | StringBuilder is not inherently thread-safe |
Example: Demonstrating the differences between String and StringBuilder
Using String Class: Geeks Using StringBuilder Class: GeeksforGeeks
Explanation:
StringBuilder object by appending new content, as it is mutable.To convert a String class object to StringBuilder class object, just pass the string object to the StringBuilder class constructor.
Example:
GeeksForGeeks
This conversions can be performed using ToString() method.
Example:
StringBuilder object to String: Builder