I've always wondered why does JAVA and C# has String
(immutable & threadsafe) class, if they have StringBuilder
(mutable & not threadsafe) or StringBuffer
(mutable & threadsafe) class. Isn't StringBuilder
/StringBuffer
superset of String
class? I mean, why should I use String
class, if I've option of using StringBuilder
/StringBuffer
?
For example, Instead of using following,
String str;
Why can't I always use following?
StringBuilder strb; //or
StringBuffer strbu;
In short, my question is, How will my code get effected if I replace String
with StringBuffer
class? Also, StringBuffer
has added advantage of mutability.
I mean, why should I use String class, if I've option of using StringBuilder/StringBuffer?
Precisely because it's immutable. Immutability has a whole host of benefits, primarily that it makes it much easier to reason about your code without creating copies of the data everywhere "just in case" something decides to mutate the value. For example:
private readonly String name;
public Person(string name)
{
if (string.IsNullOrEmpty(name)) // Or whatever
{
// Throw some exception
}
this.name = name;
}
// All the rest of the code can rely on name being a non-null
// reference to a non-empty string. Nothing can mutate it, leaving
// evil reflection aside.
Immutability makes sharing simple and efficient. That's particularly useful for multi-threaded code. It makes "modifying" (i.e. creating a new instance with different data) more painful, but in many situations that's absolutely fine, because values pass through the system without ever being modified.
Immutability is particularly useful for "simple" types such as strings, dates, numbers (BigDecimal
, BigInteger
etc). It allows them to be used within maps more easily, it allows a simple equality definition, etc.
See more on this question at Stackoverflow