Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder vs string constructor - the character

Tags:

c#

.net

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?

like image 339
Nickolodeon Avatar asked Nov 30 '11 10:11

Nickolodeon


People also ask

What is the difference between string and StringBuilder?

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.

What is difference between string and StringBuilder in C#?

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.

How does string builder work?

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.

How assign StringBuilder value to string in C#?

ToString() method in C# is used to convert the value of a StringBuilder to a String.


2 Answers

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) 
like image 191
Darin Dimitrov Avatar answered Sep 23 '22 08:09

Darin Dimitrov


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.

like image 45
Marc Gravell Avatar answered Sep 23 '22 08:09

Marc Gravell