I just saw a code like
StringBuilder result = new StringBuilder();
for (int i = 0; i < n; i++)
{
result.Append("?");
}
return result.ToString();
I know that concatenating with StringBuilder is considered faster (and does not create new instance of a string on every append). But is there any reason we would not prefer to write
return new string('?', n)
instead?
String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer.
However, whereas a string is an immutable type in C#, StringBuilder is an example of a mutable item. In C#, a StringBuilder is a mutable series of characters that can be extended to store more characters if required.
The StringBuilder works by maintaining a buffer of characters (Char) that will form the final string. Characters can be appended, removed and manipulated via the StringBuilder, with the modifications being reflected by updating the character buffer accordingly. An array is used for this character buffer.
ToString() method in C# is used to convert the value of a StringBuilder to a String.
But is there any reason we would not prefer to write
return new string("?", n)
instead
The only reason I can think of is unfamiliarity of the developer with the existence of this string constructor. But for people familiar with it, no, there is no reason to not use it.
Also you probably meant:
return new string('?', n)
The main reason not to use new string("?", n)
is that no such constructor exists and it won't compile. However, there is absolutely no reason not to use new string('?', n)
, and I fully encourage you to do so.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With