Why should I use the Stringbuilder class instead of the String class?

Asked

Viewed 718 times

13

Why these two classes are different, because it seems to me that they could be one class.

For example, the method Append, it seems to me that he does the same thing as the operator +.

1 answer

7


Basically to avoid the problem of Shlemiel the Painter’s Algorithm.

Shlemiel the painter's algorithm

To string in C# is immutable. When you add new parts to string, it is necessary to make a new memory allocation and copy all existing content to add the new content. Of course there is some optimization to not happen that much, but it happens much more than is acceptable in most situations. Imagine that each time the allocation is bigger and spending more time, making its use impractical (including because it puts pressure on Garbage Collector).

The guy StringBuilder is changeable. Then only the new parts are allocated and the object will connect these parts. When there is change in text snippets, it is effectively changed instead of creating a new text.

Of course it is not in any situation that the StringBuilder will be clearly more efficient. Many programmers who already know the problem think that any concatenation should use it, this is not true. If you know how many and which parts to concatenate, it is unnecessary to use this type. So it’s usually only more advantageous in large or potentially large ties.

Note that internally there are differences and you cannot simply use the content of a StringBuilder where you expect something like string. A conversion is necessary. So in cases of few concatenations the advantage is not great.

Some of the past information is implementation details, so it is possible that each implementation is a little different, in fact it has already worked a little differently.

It is also clear that the goal is different when we look at the methods of one type and the other. We do not have the same set of possible behaviors. Some methods make more sense in StringBuilder (the main ones are Append, Insert, Replace and Remove), which is not a suitable type to do all kinds of manipulation of string which has far more basic handling methods.

I won’t go into too much detail here because there are several answers on the subject with information that serves this question, even when you speak of another language.

More details about how it works (is Java but almost all the same).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.